RailsCasts Pro episodes are now free!

Learn more or hide this

Recent Comments

Avatar

@Anthony, fixtures are primarily used in testing. They load up your database with data so the tests have something to work with.

I personally do not use fixtures extensively because I prefer to keep my tests less dependent on external data, but there are quite a few who do use them.

Avatar

Nice example, like the simplicity...but when should I use a fixture? Surely maintaining a flat file for product/category management would be a step backwards for the shopkeeper?

Avatar

Nice work. I like the simplified div_for, and partials as well.

I'm a little confused on puts vs. post/get

Avatar

Hi Ryan.

I find this series very useful. I've implemented some stuff using the technique you've described and it works great, but I'm interested how could I make file upload using this very technique (gmail like upload). Can you help me please?

Avatar

Thank you very much, Rails Casts rule! Im new to rails, but your casts are helping my pick it up fast

Avatar

@Ryan,

Thanks for the example. I tried it and it worked with the project/tasks. However, when I tried to follow your example on task/requirements it didn't work.

I believe that in your example, it should have been <% for requirement in task.requirements %> instead of <% for requirement in @project.task.requirements %> as task doesn't exist.

I tried both, and the former returned an empty array for requirements, and the latter throws some error on the page.

Could you please show me a working example or correct me?

Today is the first time I actually play around with rails.

Thanks & regards,
voki

Avatar

@Ste You might want to start with the Agile book titled "Agile Web Development with Rails". It makes a very nice beginner course for people who have done web development with other languages and frameworks.

Have a look.

Avatar

Excellent 3-part series. I'm coming from a PHP background where I usually had a separate /admin folder, but I was stumped on the best way to do this RESTfully in Rails. This makes a lot of sense. I get it now, thanks to you!

Avatar

Right on Wes! That is the only time I ever stash a model in the session. And really at that point I don't consider it a model since a model imho is something that represents data in the DB, which is not the case in this usage. Plus doing it this way prevents hacked methods like creating a bit column in the db table to signify the row (model object) being complete.

Avatar

These railscast's truly are awesome. Monday is now my favorite day.

Avatar

@Jeroen, good questions! You'll need to create the join model fixtures for has_many :through, it won't work the same way as HABTM.

As for rSpec, fixtures work the same way there as they do with test/unit, so all of this is still valid.

Avatar

Thanks so much for another great screencast series. However, I found it a little bit complicated and cluttered with all these hidden fields, javascript and such. So I took a slightly different approach. First, I modifed the task partial so that it passes always a model id:

  <%= fields_for "project[tasks][#{task.new_record? ? 0 : task.id}]", task do |task_form| %>

Now I can determine which tasks to create, update and delete in the method task_attributes= like this:

  def task_attributes=(task_attributes)
    task_attributes.each do |id, attributes|
      if id.to_i == 0
        tasks.build(attributes)
      else
        task = tasks.detect{|p| p.id == id.to_i}
        tasks.attributes = attributes
      end
    end
    tasks.reject{|t| t.new_record? || task_attributes.has_key?(t.id.to_s)}.each {|t| t.mark_for_destroy}
  end

Works like a charm and keeps my views clean.

Avatar

Ryan, this was a terrific tutorial. I'd definitely be interested in seeing more on validations, etc.

I'm also curious as to how you might take a progressive enhancement approach. The current method seems to require Javascript. I tried using a TaskController to provide web services, but if I make it polymorphic (Project and ToDoList), all hell breaks loose... or at least, it looks really ugly.

I like the fact that nothing is lost until the entire project is saved, so I'd prefer to keep it that way, but adding and removing tasks becomes difficult without Javascript.

Avatar

One thing I noticed in the build source code for Active Record (at least in Edge Rails) is that you don't actually need to loop through task_attributes to build the tasks objects -- build will recursively do it for you.

def task_attributes=(task_attributes)
  task_attributes.each do |attributes|
    tasks.build(attributes)
  end
end

becomes

def task_attributes=(task_attributes)
  task_attributes.build(attributes)
end

Try it out.

Avatar

nice! What about has_many :through - is that managed the same way? And will this automatically work with rspec?

Avatar

Great site. All folks from our company can't wait for another piece of railscast ! Don't stop we love this site !

Avatar

Awesome. I know that when I first started using fixtures, I was wondering why these features weren't standard to begin with. I had no idea they would be in Rails 2.0. Very useful.

Avatar

Thank you for sharing
It's cool trick

Avatar

Sorry... completely off topic.

If you listen very very closely you can hear frogs in the background. I can't help but imagine that you live on a bijou ala Happy Gilmore or something busting out awesome rails nuggets of smart from your two room shack.

Avatar

Awesome screencast series, thank you so much!

Only one question.. I'm trying to do this with a habtm relationship (possible topic for another screenie? ;)) and unfortunately it doesn't save the linking table when updating attributes. :(

Does anyone have an idea how to tell rails to manually save it?

Avatar

Hey Ryan. Thou art the man. Rock on.

Avatar

Im confused a little bit. I created new column in my db called permalink. Then i did like in the video, but my urls are /5-
no permalink string. I know the problem, i dont have anything in permalink. Is this permalink generated automatically from somewhere? Or do i have to do it manually, when i create new ex. article?

Avatar

If you are looking for jQuery for Rails, check this out. http://ennerchi.com/projects/jrails

Avatar

Hi Ryan,

I got problem with rjs.

It's redirection problem ... I think.

It starts at http://localhost:3000/freddys.

And after I hit update button which send all params via form_remote_tag to server and use rjs to update current page.

However, it render at http://localhost:3000/user/update/2 and display content of the rjs file.

Any idea ... thanks

 

Avatar

This is great, but I'm only getting one record in my child table added, and the second one is not - can you explain somewhere how the tables are related?

Sorry, I'm very new to rails, and only testing really, but I'm a little bit stuck - I will move onto part 3 in the meantime.

Avatar

How do I reference the project[task_attributes][] fields for auto_complete_field functions... Does anyone have an example using auto_complete_field and fields_for?

Avatar

Hi, I am very green on Rails yet. Could someone explain what is the issue with this approach and caching?

Thanks,

Ryan, great job!!

Avatar

ALmost forgot to mention, I only have this problem when I have the marked_for_destroy hidden field and js link in that partial. I remove them and can add tasks with no problem. Odd..

Avatar

Strange problem here..

I can edit and delete tasks with no problem, but when I try to create a new task (or several at once) the very first of the previously saved tasks gets wiped out. I copied Ryan's code line for line and am running this in Rails 2.0.

Anyone else face this issue?

Avatar

Hi Ryan, I searched for hours on how to do custom actions (outside the standard 7) but with no success. Until I found your podcast - thank you!

Avatar

@Jose
in addition to what QuBit said:
xyz.js.erb for Javascript-generating files in the views
xyz.erb for mail-generating files in the views

Avatar

@Mathijs
...#6432 from the changelog
url_for([parent, child])
generates /parents/1/children/2 for the nested resource.
Likewise with the other simply helpful
methods like
form_for
and
link_to.

Avatar

Hey, thanks a lot QuBiT, very helpful.

Ryan, great work as usual!

Avatar

any plan for using jquery instead of prototype?

Avatar

@Paul, I agree this is an over-refactoring. It works best if you have quite a few of these kinds of actions in multiple controllers. That scenario was too complex for a simple screencast so I stuck with one controller.

In this case it's more about the technique then the circumstances to use it (which varies from project to project). I should have made that more clear.

@lester, LOL. I said "dig" around. I'll blame it on the cold I'm getting.

Avatar

@Mathijs, try this:

form_for [@person, @article]

I normally don't use nested resources so I'm not certain this will work.

@Andy, the map.resources method supports a :path_prefix option. Try using that:

map.resources :toys, :path_prefix => 'products'

Untested.

@Rupak, yep, form_for works great when placed in a partial. That's what I usually do.

Avatar

Cheers Cliff, I think I found out what he's doing via another cast :) http://media.railscasts.com/videos/034_named_routes.mov

Avatar

Ryan -

Thanks for the great screencasts.

I was a bit confused by the workaround in the should_destroy? method, until I remembered that MySQL lacks a genuine BOOLEAN datatype.

With PostgreSQL, you can define a boolean field in your model (without a trailing ?), and a predicate method (with the trailing ?) is automatically there in your model. Handy.

Avatar

@Chris Lock: Perhaps you need "map.resources :projects" at the top of your config/routes.rb file?

Avatar

I'm getting an "undefined local variable or method 'task'" error when trying to save the form.

Any ideas what I might have missed?

Avatar

@Jose .. just rename your rhtml files to html.erb, and your rxml to xml.builder and everything will work well or just use this code:

[code]
  task :rhtml2erb do
    desc 'Renames all your rhtml views to erb'
    Dir.glob('app/views/**/*.rhtml').each do |file|
      puts `svn mv #{file} #{file.gsub(/\.rhtml$/, '.html.erb')}`
    end
  end
[/code]

Everyone who want to use the latest version of rails has just to use this in his application root folder:

[code]
"svn co http://dev.rubyonrails.org/svn/rails/trunk vendor/rails"
[/code]

it will checkout the latest version from trunk and puts it into vendor/rails ... rails will check if it is available automatically before it uses the installed version.

one remark -> (the version aufter 8165 seems to have one bug and does not work correct today, but maybe they correct it until tomorrow)
so append "--revision 8165" to the upper command.

Avatar

I mean, why the use of the filename ".html.erb"?

PS: sorry for the many posts, this keyboard doesn't behave well...

Avatar

Ok...I feel stupid, can someone give me links or explain a little bit of ERB?

Avatar

Since mew.html.erb and edit.html.erb share the same code except the Title maybe, can we replace the foll. code with a partial like <%= render :partial => "form" %>?

<!-- new.html.erb and edit.html.erb -->
<% form_for @product do |f| %>
  ...
<% end %>

Will the system be smart enough to detect if it is the case of new or edit from within the partial?

Avatar

One thing that annoys me about the rails 2 view shortcuts is when using restful nested controllers.
Maybe I'm just doing something wrong.

routes.rb:
map.resources :people,
  :has_many => :written_articles

now, in views for my WrittenArticlesController, I can't use form_for @article anymore.
Neither can I use link_to 'Show', @article anymore.

I have to revert to person_written_messages_path(@person, @article) which is silly.

This isn't the worst,
It is far worse that form_for @article won't work anymore (which is very nice to have, because new and edit can use the same form) and I have to revert to full paths again, and _manually_ tell the form to use PUT or POST.

Am I doing something wrong here? Wouldn't it be much cleaner for rails to just assume (since it's rendering a view for the written_articles controller) I'm talking about the @article in scope of the person who wrote it? And then if I really want to link to the message itself force me to use article_path(@article) ?

Avatar

please give us more info on rails 2.0. i just can't wait for the final RC.

Avatar

Thanks for the video, I like this one.

But I have a question. This with REST is very confusing. If I have created a controller for example "ruby script/generate controller products/toys". How do I write in route.rb? I can't write "map.resources :products/toys".