ruby-on-railsrubyattr-accessor

Assign_attributes only assigns child attr_accessor values if a table column is changed on updates


Here's the set up

class Order
  has_many :items
  accepts_nested_attributes_for :items
end

class Item
  belongs_to :order
  attr_accessor :discount # this is NOT a table column, just a virtual attribute I want to be able to assign
end

Let's say I have an existing order @order. I noticed that if I were to try to assign discount on the child Item from the Order model, this only works if some other attribute on the child Item is changed.

@order.assign_attributes({"items_attributes"=>[{"id"=>40, "discount"=>"test"}]})
@order.items.first.discount
=> nil

@order.assign_attributes({"items_attributes"=>[{"id"=>40, "discount"=>"test", "admin_notes"=>"hello"}]})
# where admin_notes is a table column for Item
@order.items.first.discount
=> "test
@order.items.first.admin_notes
=> "hello"

Is there a quick setting change or something to change this? I'd like attr_accessor attributes to always be assigned even if no attributes are changing?


Solution

  • FWIW if anyone stumbles upon this.... it appears to have resolved itself. Was working on something else today and noticed that I can't duplicate the original error anymore. A lot has changed in code, not going to go back and dig into this to figure out what happened. I do know that key configuration variables that could have affected this have not changed, e.g., inverse_of flag set on both models, Order model set to accepts_nested_attributes_for :items