2016-03-25 23 views
0

我有一個Company模型,它有lending_restricted:boolean列。 關於限制的清單通過restricted_codes方法收集。如何在Rails中有效地更新多個實例

,並更新只在必要的公司,我寫的是這樣的:

old_codes = Company.where(lending_restricted: true).pluck(:code) 
new_codes = restricted_codes 
(new_codes - old_codes).each do |code| 
    c = Company.find_by(code: code) 
    c.try(:update_attributes, lending_restricted: true) 
end 
(old_codes - new_codes).each do |code| 
    c = Company.find_by(code: code) 
    c.try(:update_attributes, lending_restricted: false) 
end 

它的工作原理基本上都是精品,但我覺得這是一個有點多餘寫類似功能的兩倍。 有沒有更好的方法來編寫這樣的方法?

restricted_codes的數量約爲100,我的Rails項目中有大約4000家公司。

回答

2

未經測試,但也許是這樣的?我還更新了代碼,以便在一個查詢中完成(而不是N個查詢)。

def update_lending_restriction(codes, restriction) 
    Company.where(code: codes).update_all(lending_restricted: restriction) 
end 

old_codes = Company.where(lending_restricted: true).pluck(:code) 
new_codes = restricted_codes 

update_lending_restriction(new_codes - old_codes, true) 
update_lending_restriction(old_codes - new_codes, false) 
相關問題