考虑一下这种情况:
Butterfly.create(:color='blue')
此时,正如预期的那样,蝴蝶(在内存中)是蓝色的,而相应的数据库对象是红色的。现在尝试更新数据库条目。
结果是大小属性被更新,但是颜色没有更新。剩下的情况是,即使在成功保存或update_attributes之后,数据库也与内存中的对象不匹配。事实上,即使是butterfly.update_attribute(:color, 'blue')也不足以强制对数据库进行更改!我看到强制执行的唯一方法是首先将属性更新为其他东西(butterfly.update_attribute(:color,'anything')),然后将其更改为原始值。
事情应该是这样的吗?
发布于 2011-06-09 07:52:19
差不多吧。
Model.update_all直接向底层数据库发出更新查询;它不会更新内存中已有的任何实例。类似地,instance.update_attributes只更新-它不从数据库中重新获取,因为它假设实例已经拥有最最新的属性值。
这通常适用于Rails,实例通常是短暂的:它们只存在于请求的范围内,而且在大多数情况下,它们都是直接操作的。
在上面描述的情况下,您需要额外的步骤--Model#reload可以做您想做的事情:
# create our instance
@butterfly = Butterfly.create(color: 'blue') # => #<Butterfly id: 100, color: 'blue'>
Butterfly.update_all(color: 'red')
# We now have a mis-match between our instance and our database. Our instance
# is still blue, but the database says it should be red. Reloading it...
@butterfly.reload # => #<Butterfly id: 100, color: 'red'>
# And we can now re-update our butterfly
@butterfly.update_attributes(size: 'big') # => #<Butterfly id: 100, color: 'red', size: 'big'>如果您使用的是update_all,那么最好看看是否有可能构造您的代码,以便在加载实例之前实现。
https://stackoverflow.com/questions/6289531
复制相似问题