如何避免覆盖嵌套属性?

时间:2015-08-20 18:13:45

标签: ruby-on-rails ruby-on-rails-4 activerecord nested-forms nested-attributes

我有:

SELECT CONCAT(AdminLastName,',',AdminFirstName)
FROM Admins
WHERE AdminID NOT IN(SELECT AdminID FROM Servers)

class Activity < ActiveRecord::Base
  has_and_belongs_to_many :balance_sheets
end

当我执行UPDATE发送class BalanceSheet < ActiveRecord::Base has_and_belongs_to_many :activities accepts_nested_attributes_for :activities end 时,如果我在balance_sheet对象上加载了先前的活动,则会替换活动集合。 我不想覆盖活动旧值,我想添加新值。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

不要直接更新BalanceSheet对象。而是创建一个中间的BalanceSheetUpdater类,它将使用activity_ids并将其附加到现有的balance_sheet activity_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