Ruby-on-rails 如何在不担心主键的情况下更新记录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2710867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to update a record without worrying about primary key
提问by railsnew
In ActiveRecord how can we update a record without worrying/knowing primary key.
在 ActiveRecord 中,我们如何在不担心/知道主键的情况下更新记录。
If I do
如果我做
Address.update(15, :user_name => 'Samuel')
it corresponds to
它对应于
UPDATE addresses set user_name = 'Samuel' where id = 15
but what if i want to do:
但如果我想做:
UPDATE addresses set user_name = 'Samuel' where cid = 15
what will be the ActiveRecord equivalent of that??
什么是 ActiveRecord 等价物?
I tried:
我试过:
Address.update({:cid => 15}, :user_name => 'Samuel')
but that does not work.
但这不起作用。
回答by typeoneerror
Use the update_allclass method:
使用update_all类方法:
Address.where(:cid => 15).update_all(user_name : 'Samuel')
回答by Francisco Soto
a = Address.find_by_cid(15)
a.user_name = 'Samuel'
a.save
回答by boulder_ruby
To clarify on @typeoneerror's answer, just use update_allon an ActiveRecord::Relation object rather than a record object:
为了澄清@typeoneerror 的答案,只需update_all在 ActiveRecord::Relation 对象而不是记录对象上使用:
ModelName.where(:unique_id => x).update_all(:name => "x")

