17
def update
  @album = Album.find(params[:id])
  if @album.update_attributes(params[:album])
    redirect_to(:action=>'list')
  else
    render(:action=>'edit')
  end    
end

A Rails 1.1.6 tutorial that I'm covering recommends using the update_attributes method for updating a model, as in the example code from my controller listed above. Looking at the Rails documentation I'm wondering why the update method would not have been preferred, especially since it is named so logically.

JJD
  • 50,076
  • 60
  • 203
  • 339
pez_dispenser
  • 4,394
  • 7
  • 37
  • 47
  • 1
    This article about *[5 Ways To Set Attributes In ActiveRecord](http://www.davidverhasselt.com/2011/06/28/5-ways-to-set-attributes-in-activerecord/)* might of interest. – JJD Jul 23 '13 at 10:06

2 Answers2

26

Update takes an object id parameter and a set of attributes that otherwise work like update_attributes.

So this (from AWDWR 3rd edition)

Order.update(12, :name => "Barney", :email => "barney@bedrock.com")

is equivalent to

Order.find(12).update_attributes(:name => "Barney", :email => "barney@bedrock.com")

So if all you want to do is update a row of known id with a set of attributes then I'd say there's no reason not to use update - it looks like that's the reason they wrote it!

(Is there any way you can get your tutorial to upgrade from 1.1.6? It's pretty old and wasn't a particularly earth-shattering release when it was current. 1.2.6 was better - the last of the 1.xs, if I remember correctly).

Mike Woodhouse
  • 51,832
  • 12
  • 88
  • 127
  • 1
    Thanks for the code snippet - that makes sense. No, it's not upgradeable, unfortunately. It's a lynda.com video series - it's really quite a good introduction to Rails for me although I will probably need to read a more up-to-date text after I finish it. First I need to understand the Big Picture, which I had been having a hard time with after reading the O'Reilly book "Head First Rails" a few months back. – pez_dispenser May 08 '09 at 15:29
0

Using update_attributes method just suppose that you already have an object, and you would just pass the set of attributes. And the work is done !

babttz
  • 446
  • 4
  • 11