2014-05-16 30 views
1

在Rails 3.2控制台中,我试图将几个记录更新为相同的值。阵列的Rails 3 update_attributes

例如:

h=Person.find_all_by_company_country("Alabama") 

现在我想改变company_country为 “得克萨斯”

例如:

h.update_attributes(company_country: "Texas") 
NoMethodError: undefined method `update_attributes' for #<Array:0x00000003b01d70> 

什么是做到这一点的选择?

+0

不会更新所有人员属性。我只想要与阿拉巴马州的人改变 – DDDD

回答

1

更换你的方法find_all_by_company_country使用活动记录querys代替,这样你就可以回到一个关系。

h = Person.where(company_country: "Alabama") 

然后简单地调用:

h.update_all company_county: "Texas" 

不过,请注意update_all不调用活动记录的回调。如果你需要回调&验证火灾,而是使用:

h.each { |record| record.update_attributes({ company_country: "Texas" }) } 
+0

ActiveRecord查询,+1。良好的信息。 – DDDD

1

正如你可以在输出中看到,从find_all*方法的结果返回一个数组对象,其中不具备update_attributes方法。

只是作为一个例子,来修改阵列中的每个记录,你会重复这样的每一条记录:

Person.find_all_by_company_country("Alabama").each do |record| 
    record.update(:company_country => "Texas") 
end 

但典型的方式是与whereupdate_all方法执行更新,这是通过使用单个更新查询,效率更高:

Person.where(:company_country => "Alabama").update_all(:company_country => "Texas")