如何在不担心主键的情况下更新记录

时间:2023-01-11 02:10:10

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.

但这不起作用。

4 个解决方案

#1


15  

a = Address.find_by_cid(15)
a.user_name = 'Samuel'
a.save

#2


43  

Use the update_all class method:

使用update_all类方法:

Address.where(:cid => 15).update_all(user_name : 'Samuel')

http://apidock.com/rails/ActiveRecord/Relation/update_all

http://apidock.com/rails/ActiveRecord/Relation/update_all

#3


8  

To clarify on @typeoneerror's answer, just use update_all on an ActiveRecord::Relation object rather than a record object:

要澄清@typeoneerror的答案,只需在ActiveRecord :: Relation对象而不是记录对象上使用update_all:

ModelName.where(:unique_id => x).update_all(:name => "x")

#4


-4  

http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002273

http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002273

#1


15  

a = Address.find_by_cid(15)
a.user_name = 'Samuel'
a.save

#2


43  

Use the update_all class method:

使用update_all类方法:

Address.where(:cid => 15).update_all(user_name : 'Samuel')

http://apidock.com/rails/ActiveRecord/Relation/update_all

http://apidock.com/rails/ActiveRecord/Relation/update_all

#3


8  

To clarify on @typeoneerror's answer, just use update_all on an ActiveRecord::Relation object rather than a record object:

要澄清@typeoneerror的答案,只需在ActiveRecord :: Relation对象而不是记录对象上使用update_all:

ModelName.where(:unique_id => x).update_all(:name => "x")

#4


-4  

http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002273

http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002273