简体   繁体   English

相同模型的最佳实践是什么:update_attributes或self.save

[英]What is the best practice for same model: update_attributes or self.save

Say I have to update 'author_id' in article model. 假设我必须在文章模型中更新“ author_id”。 From a method that belongs to app/model/article.rb 来自属于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! 如果有更好的方法,请提出建议!

The main difference is that update_attribute will not trigger validations. 主要区别在于update_attribute将不会触发验证。 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): 您可以使用update_attributes编写一行(末尾为s):

self.update_attributes(author_id: id)

There is also another methods worth knowing called update_column(s) . 还有另一种值得了解的方法称为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!

It depends. 这取决于。 If you want your validations run, you should go with the second way (with save ): 如果您想运行验证,则应采用第二种方法(使用save ):

self.author_id = id
save

You can do it also in one line, using update : 您也可以使用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 (因为update_attribute不运行验证):

update_attribute(:author_id, id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM