Ruby on rails Rails-动态添加更多嵌套属性
这似乎是一个相当琐碎的问题,但我无法解决这个问题。我有两张发票和发票项目表。在发票模型中:Ruby on rails Rails-动态添加更多嵌套属性,ruby-on-rails,Ruby On Rails,这似乎是一个相当琐碎的问题,但我无法解决这个问题。我有两张发票和发票项目表。在发票模型中: accepts_nested_attributes_for :invoice_items, allow_destroy: true, reject_if: :all_blank 现在,在基于某些条件的方法中,我希望动态添加更多发票项。在before_save回调中,我正在执行以下操作: def process_amounts if condition_holds self.invoice_i
accepts_nested_attributes_for :invoice_items, allow_destroy: true, reject_if: :all_blank
现在,在基于某些条件的方法中,我希望动态添加更多发票项。在before_save回调中,我正在执行以下操作:
def process_amounts
if condition_holds
self.invoice_items_attributes << {key_1: value_1, key_2: value_2} # Pseudo code.
end
end
以上代码将产生3项结果!它不会重新分配发票项目属性
那么如何解决这个问题呢?发票项目属性仅在paramsController中可用。您可以在中的模型invoice中执行此操作,然后像这样保存回调 保存前:处理金额
def process_amounts
if condition_holds
self.invoice_items.build([{key: value, key2: value2},{key: value, key2: value2}])
end
试试这个
if condition_holds
self.invoice_items << InvoiceItem.new(key_1: value_1, key_2: value_2)
end
我假设InvoiceItem是发票项的模型名
if condition_holds
self.invoice_items << InvoiceItem.new(key_1: value_1, key_2: value_2)
end