I have a model called UserPrice and I want to let users be able to create many of the same resources on one form using just the UserPrice model.
Success
Working Code: ( this code will create x amount of user_prices but will not show error messages/validate or reject if certain fields are blank.)
class UserPricesController < ApplicationController
def new
@user_prices = Array.new(5) { UserPrice.new }
end
def create_multiple
@user_prices = params[:user_prices].values.collect { |user_price| UserPrice.new(user_price) }
if @user_prices.all?(&:valid?)
@user_prices.each(&:save!)
redirect_to :action => :new, :notice => "Successfully created product."
else
redirect_to :back, :notice => "Error."
end
end
resources :user_prices do
post :create_multiple, :on => :collection
end
<%= form_tag create_multiple_user_prices_path, :method => :post do %>
<% @user_prices.each_with_index do |user_price, index| %>
<%= fields_for "user_prices[#{index}]", user_price do |up| %>
<%= render "add_user_price_fields", :f => up %>
<% end %>
<% end %>
<%= submit_tag "Done" %>
<% end %>
The problem is in your controller method
create_multiplewhere you’re only creating one object.You should try something like this:
Source