0

我:如何避免覆蓋嵌套屬性?

class Activity < ActiveRecord::Base 
    has_and_belongs_to_many :balance_sheets 
end 

class BalanceSheet < ActiveRecord::Base 
    has_and_belongs_to_many :activities 
    accepts_nested_attributes_for :activities 
end 

我,如果我有加載balance_sheet對象上以前的活動執行UPDATE發送"balance_sheet"=>{"activity_ids"=>["10", "20"]},活動集合被替換。 我不想覆蓋活動的舊值,我想添加新的。我怎樣才能做到這一點?

回答

0

不要直接更新BalanceSheet對象。相反,創建一箇中間BalanceSheetUpdater類,它將把您的activity_ids並附加到現有的balance_sheetactivity_ids

class BalanceSheetUpdater 
    def initialize balance_sheet 
    @balance_sheet = balance_sheet 
    end 

    def call(balance_sheet_params) 
    new_ids = balance_sheet_params.delete("activity_ids") 
    update_status = @balance_sheet.update(balance_sheet_params) 

    if update_status 
     existing_ids = @balance_sheet.activity_ids 
     @balance_sheet.update(existing_ids + new_ids) 
    end 

    update_status 
    end 
end 

# controller 
updater = BalanceSheetUpdater.new(@balance_sheet) 
if updater.call(balance_sheet_params) 
    ... # success/fail actions