Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

override nested attributes in rails

what happens when I override nested attributes method in rails. For example,

class Order
  has_many :line_items
  accepts_nested_attributes_for :line_items

  def line_item_attributes=(attr)
   # what can I do here.
  end
end

class LineItem
  belongs_to :order
end

In the above code ,

  1. Inside line_item_attributes= method, can I add/modify/delete line items of the order?
  2. When is line_items_attributes= invoked, if I call @order.save(params) ?
like image 338
Anand Avatar asked Jan 23 '12 08:01

Anand


1 Answers

Use an alias

In Rails 4, you can override and call super.

In earlier versions, you can use Ruby's alias:

class Order
  has_many :line_items
  accepts_nested_attributes_for :line_items

  # order of arguments is new_name, existing_name
  alias :original_line_items_attributes= :line_items_attributes=
  def line_items_attributes=(attrs)
   modified_attributes                 = my_modification_method(attrs)
   self.original_line_items_attributes = modified_attributes
  end

end
like image 122
Nathan Long Avatar answered Oct 01 '22 15:10

Nathan Long