views:

202

answers:

1

I would like to get some nested params. I have an Order that has many Items and these Items each have a Type. i would like to get the type_id parameter from the controllers create method.

@order = Order.new(params[:order])
@order.items.each do |f|
  f.item_type_id = Item_type.find_by_name(f.item_type_id).id
end

The reason is that i want the user to be able to create new item_types in the view. When they do that i use an AJAX call add them to the db. When they post the form i get names of the item_type in the item_type_id parameter and i want to find the correct item_type and set the id to that

+1  A: 

To access the nested fields from params do the following:

params[:order][:items_attributes].values.each do |item|
  item[:type_id]
end if params[:order] and params[:order][:items_attributes]

Above solution will work ONLY if you have declared the correct associations and accepts_nested_attributes_for.

class Order < ActiveRecord::Base
  has_many :items
  accepts_nested_attributes_for :items, :allow_destroy => true
end

class Item < ActiveRecord::Base
  belongs_to :order
end
KandadaBoggu
@KandadaBoggu! love love
macek
Seems like that is what i need. However, i get a undefined method `values' for nil:NilClass - error
Flexo
It looks like `params` does not have `items_attributes`. Print `params` to check the value.
KandadaBoggu
Parameters: {"authenticity_token"=>"61m5JPrQ3ZS3fxAxoh1cgmmhO5U+WCcYZ2RykLIHc3o=", "order"=>{ "items_attributes"=> {"1270891910372"=> {"price"=>"", "text"=>"", "amount"=>"", "kind_id"=>"Bla", "_destroy"=>""} }, "total_price"=>"2"}}
Flexo
You have to extract the :order first. Also I don't see `type_id` in the `items_attributes`. I have updated my answer take a look.
KandadaBoggu