My controller is not saving correctly array params.
Database
|categories|
|id| |name|
1 HW
2 SF
3 PC
|products|
|id| |amount| |category_id|
But after saving the table 'PRODUCTS', should save array params will be like this demo
|products|
|id| |amount| |category_id|
1 100 1
2 200 2
3 300 3
Controller:
def new
@categories = Category.all
@obj_product = Product.new(params[:obj_product])
end
def create
params[:obj_product].each do |key , value|
o = FlowBudgetDetail.new( :amount => value , :category_id => key)
o.save
end
if o.save()
redirect_to :action=>"index"
else
redirect_to :action=>"new"
end
end
View:
<% form_for :obj_product, :url => {:action=>'create'} do |f| %>
<% @categories.each do |category| %>
<%= f.text_field :category_id , :name => "obj_product[array_#{category.id}][category_id]"%>
<%= f.text_field :amount , :name => "obj_product[array_#{category.id}][amount]" %>
<% end %>
<$ end %>
Log is showing all parameters but is just creating one insert:
Processing ProductController#create (for 127.0.0.1 at 2015-08-07 17:23:26) [POST]
Parameters: {"commit"=>"Save", "obj_product"=> {"array_1"=>{"amount"=>"100","category_id"=>"1"},"array_2"=>{"amount"=>"300","category_id"=>"2"},"array_3"=>{"amount"=>"300","category_id"=>"3"} }}
INSERT INTO `products` (`category_id`, `amount`) VALUES( 0, 1)
INSERT INTO `products` (`category_id`, `amount`) VALUES( 0, 1)
INSERT INTO `products` (`category_id`, `amount`) VALUES( 0, 1)
This should save this:
INSERT INTO `products` (`category_id`, `amount`) VALUES( 1, 100)
INSERT INTO `products` (`category_id`, `amount`) VALUES( 2, 200)
INSERT INTO `products` (`category_id`, `amount`) VALUES( 3, 300)
Is saving incorrect information (incorrect params)
Please somebody can help me?
Productstable as having two columns, then it looks like it should have 3 columns after your save? Can you clarify this?require(...).permit(....part.attr_accessor.