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家公司。