2014-05-16 31 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")