1

Say I have to update 'author_id' in article model. From a method that belongs to app/model/article.rb

Which one should i prefer and why?

self.update_attribute(:author_id, id)

or

self.author_id = id
self.save

If there is even better way, please suggest!

shivam
  • 16,048
  • 3
  • 56
  • 71

2 Answers2

5

The main difference is that update_attribute will not trigger validations. You should definitively prefer the second option (unless you really want to skip the validations). You can write in one line using update_attributes (note s at the end):

self.update_attributes(author_id: id)

There is also another methods worth knowing called update_column(s). Those method will skip all the callbacks and validations and will save only specific columns in the database, leaving the rest unchanged (all other methods saves all the columns):

self.id    #=> 1
self.id = 5
self.update_column(:name, 'hello')
self.id    #=> 5
self.id_changed?    #=> true!
BroiSatse
  • 44,031
  • 8
  • 61
  • 86
  • `update_attributes` does trigger callbacks, it only doesn't run validations. – Marek Lipka May 21 '14 at 07:54
  • thanks a lot. I really didn't know this about update_column. I think it should be best in my case, where i dont need any callbacks and validation and all i need to do is update a specific column! +1 – shivam May 21 '14 at 08:27
  • @singhshivam - Just remember to be careful when you use them as they can easily make your stored models invalid. – BroiSatse May 21 '14 at 08:29
  • thanks i will be careful. Also i found this: update_attributes tries to validate the record, calls callbacks and saves; update_attribute doesn't validate the record, calls callbacks and saves; http://stackoverflow.com/questions/14415857/rails-update-column-works-but-not-update-attributes Hope its helpful. :) – shivam May 21 '14 at 08:32
  • @MarekLipka The documentation for `update_attributes` says "If the object is invalid, the saving will fail and false will be returned". Correct me if im wrong, but doesnt this mean that it invokes validations? – Santhosh May 21 '14 at 08:51
  • 1
    @Santosh - He meant `update_attribute`, not `update_attributes`. :) – BroiSatse May 21 '14 at 08:53
1

It depends. If you want your validations run, you should go with the second way (with save):

self.author_id = id
save

You can do it also in one line, using update:

update(author_id: id)

If you don't need them, you can use update_attribute (since update_attribute doesn't run validations):

update_attribute(:author_id, id)
Marek Lipka
  • 50,622
  • 7
  • 87
  • 91
  • is there any difference in terms of performance, complexity? Which one will be more optimized? (say no validation needed) or it just comes to ones style of coding? – shivam May 21 '14 at 07:55
  • 1
    If no validation is needed, `update_attribute` is more eficient (since it doesn't run validations). – Marek Lipka May 21 '14 at 07:57