我有一个名为UserPrice
的模型,我想让用户只使用UserPrice
模型在一个表单上创建许多相同的资源。
工作代码:(此代码将创建x个user_prices,但如果某些字段为空,则不会显示错误消息/验证或拒绝。)
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 %>
答案 0 :(得分:2)
问题在于你的控制器方法create_multiple
,你只创建了一个对象。
你应该尝试这样的事情:
def create_multiple
@user_prices = params[:user_prices].values.collect { |up| UserPrice.new(up) }
if @user_prices.all?(&:valid?)
@user_prices.each(&:save!)
format.html { redirect_to(:back, :notice => 'Successfully added prices.') }
format.xml { head :ok }
else
# ...