0

I have the following create method:

def new
   @stores = Store.where(:store_id => @store.id)
   @product = Product.new(id: @store.id)
end

def create

   @product = Product.new(product_params)
   @product.store_id = params["store_id"]

   if @product.save
     redirect_to table_products_path, notice: 'product was successfully created.' 
   else
     render action: 'new'
   end

end

and a form that looks like:

<%= form_for [@table, @product] do |f| %>

  <% @stores.each do |store| %>
     <%= hidden_field_tag :store_id, store.id %>
     <%= f.label :product_price %><br>
     <%= f.text_field :product_price %>
  <% end %>

  <%= f.submit %>

<% end %>

and the models:

class Store < ActiveRecord::Base
  belongs_to :table
  has_many :products

end

class Product < ActiveRecord::Base
  belongs_to :store
end

Basically, for each store there is, I want a product to be created. Right now, the only product_price that gets saved is the last one. So for example, if there are three stores, and I enter in the product_price text fields for each one, it only saves the last.

Thanks for any and all help!

the_
  • 1,183
  • 2
  • 30
  • 61

1 Answers1

1

You're overriding your form fields by having multiple product_price and store_id inputs. Browser sends only the last one. Check out this question: Multiple objects in a Rails form

Once you're done with that, change your controller action to something like this:

Store.where(:store_id => @store.id).each do |store|
  Product.create(params[store.id][:product])
end

Hope you get the idea.

Community
  • 1
  • 1
Bart
  • 2,606
  • 21
  • 32