In my code below I want to assign the current user to the products that are created.
ProductsController.rb
def new
@products = Array.new(2) { Product.new }
end
def create_multiple
params[:product][:user_id] = current_user.id
Product.transaction do
begin
@products = Product.create!(params[:products].map {|_k, up| up.merge params[:product]})
redirect_to :back, :notice => "Success!"
rescue ActiveRecord::Rollback
redirect_to :back, :notice => "An error occured, please try again."
end
end
end
new.html.erb
<%= form_tag create_multiple_products_path, :method => :post do %>
<%= date_select("product", "purchase_date") %>
<% @products.each_with_index do |product, index| %>
<%= fields_for "products[#{index}]", product do |up| %>
<%= render "fields", :f => up %>
<% end %>
<% end %>
<%= submit_tag "Done" %>
<% end %>
The USER ID (current user) isn’t being assigned. Any ideas on how to assign it?
You can eliminate a lot of logic here by remembering two facts:
createwill take an array of Hashes to create multiple objects, and its bang-method counterpartcreate!will throw an exception if any validations failed.One way to get deal with the
create!issue is to just get rid of any “blank” entries in abefore_filter, e.g.: