Rails 3:write_attribute 和 update_attribute 之间的区别
直到今天我才知道 write_attribute...
看起来像 update_attribute,尽管不调用验证仍然调用 :before_save 回调,而 write_attribute 则不会。
这就是这两种方法的区别吗?
I did not know about write_attribute until today...
it seems like update_attribute, although not calling validation is still calling the :before_save callbacks, whereas write_attribute doesn't.
Is that the difference between these two methods?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您想要覆盖方法的默认访问器时,请使用
write_attribute
。它本质上是 self[:attribute]=(value) 的语法糖。请查看“覆盖默认访问器”标题下的 ActiveRecord::Base 文档。
如果您尝试使用 update_attribute 重写文档中的示例,我想它最终会陷入循环。
write_attribute
is used when you want to overwrite the default accessors for a method. It is essentially syntactic sugar forself[:attribute]=(value)
.Have a look at the ActiveRecord::Base documentationunder the heading "Overwriting default accessors".
If you tried to rewrite the example in the documentation using
update_attribute
, I'd imagine it would end up in a loop.update_attribute
实际上对数据库进行了物理调用。您将完全执行UPDATE
语句。它类似于update_attributes
但仅适用于单个列。而
write_attribute
则写入用于分配给基于 AR 的列的模型的属性。如果您要覆盖基于数据库的属性。我没有广泛研究
write_attribute
,但我收集基于 Activerecord 的模型处理对基于数据库的列的分配与您的普通访问器略有不同。update_attribute
actually makes a physical call to the DB. You get a full execution of anUPDATE
statement. It's likeupdate_attributes
but just for a single column.While
write_attribute
writes the attribute for assignment to the model for AR based columns. If you were to overwrite a DB based attribute.I have not looked into
write_attribute
extensively, but I gather Activerecord based models handle assignments to db based columns slightly differently than your run of the mill accessor.