ruby on rails - accepts_nested_attributes_for and second-order associations, nested forms -
i have following models associations:
class order < activerecord::base has_many :guests has_many :customers, :through => :guests accepts_nested_attributes_for :customers end class customer < activerecord::base has_many :guests has_many :orders, :through => :guests has_many :slips accepts_nested_attributes_for :slips end class slip < activerecord::base belongs_to :order belongs_to :customer end class guest < activerecord::base belongs_to :order belongs_to :customer end my nested form looks this:
<!-- general form --> <%= form_for(@order) |f| %> <% f.fields_for :customers |builder| %> <%= render "customer_fields", :f => builder %> <% end %> <%= f.submit %> <% end %> <!-- partial customer_fields --> <p> <%= f.label :name%><%= f.text_field :name %> <% f.fields_for :slips |builder| %> <%= render "slip_fields", :f => builder %> <% end %> </p> <!-- partial slip_fields --> <p><%= f.label :quantity%><%= f.text_field :quantity %></p> with setup saving order works expected, need order_id saved slip, have reference between order <-> slip. setup loose reference. can associated customers, i'll associated slips of customer related order or not.
here fields of models: order -> id
customer -> id
guest -> id, order_id, customer_id
slip -> id, order_id, customer_id
the result of order should this
- order
- customer
- slip 1
- slip 2
- customer b
- slip 1
- slip 2
- customer
- slip 1
- slip 2
- slip 3
- customer
i've no idea how accomplish this.
as far can't return order_id order isn't exist can hook (i haven't test it, you'll maybe need fix it)
def create customers = params[:order].delete :customers_attributes @order = order.new params[:order] if @order.save customers.each{|c| c[:slips_attributes].each{|s| s[:order_id] = @order.id} } @order.customers_attributes = customers @order.save end end def update @order = order.find params[:id] params[:order][:customers_attributes].each{|c| c[:slips_attributes].each{|s| s[:order_id] = @order.id} } @order = order.update_attributes params[:order] @order.save end also you'd better remove logic model , can dry little. understanding approach.
upd id collisions. scetch again
def create customers = params[:order].delete :customers_attributes @order = order.new params[:order] @order.customer_ids = customers.inject([]){|a,h| << h[:b] if h[:b]; a} if @order.save customers.each{|c| c[:slips_attributes].each{|s| s[:order_id] = @order.id} } @order.customers_attributes = customers @order.save end end def update @order = order.find params[:id] @order.customer_ids = params[:order][:customers_attributes].inject([]){|a,h| << h[:b] if h[:b]; a} params[:order][:customers_attributes].each{|c| c[:slips_attributes].each{|s| s[:order_id] = @order.id} } @order = order.update_attributes params[:order] @order.save end
Comments
Post a Comment