我敢肯定我在想这个问题,但我似乎无法弄清楚如何简单地创建和提交一次多个记录。我有一个用户模型和一个预测模型。用户has_many预测,并且预测属于用户。当我访问用户/ 1 /预测/新的,我需要创建6条预测记录,并立即提交他们的分贝我嵌套像这样多个记录提交没有嵌套
:resources users do
:resources predictions
end
我的路线。
在我的预测控制器:
before_filter :load_user
def new
3.times { @user.predictions.build }
end
def create
@prediction = @user.predictions.new(params[:prediction])
if @prediction.save
redirect_to @user, :notice => 'Prediction added'
else
redirect_to @user, :notice => 'Unable to add'
end
end
def destroy
@prediction = @user.prediction.find(params[:id])
@prediction.destroy
redirect_to @user, :notice => "Prediction deleted"
end
private
def load_user
@user = current_user
end
在我的预测new.html.erb:
<%= form_for ([@user, @user.predictions.new]) do |f| %>
<div class="fields">
<%= f.label :position %>
<%= f.text_field :position %>
</div>
<div class="fields">
<%= f.label :athlete_id, 'Athlete'%>
<%= f.collection_select(:athlete_id, Athlete.all, :id, :name, :prompt => 'Select an athlete')%>
</div>
<div class="fields">
<%= f.label :race_id, 'Race'%>
<%= f.collection_select(:race_id, Race.upcoming, :id, :name, :prompt => 'Select a race')%>
</div>
<div class="actions"><%= f.submit %></div>
<% end %>
这说明,并提交只有一个记录,而不是3,我想我可能要使用:accepts_nested_attributes_for,但是我不需要同时创建和更新用户模型。现有用户将一次创建3条记录,用于多场比赛,因为这是一款梦幻体育应用。
为什么你不想使用嵌套窗体?看起来他们完全适合你的问题。 –
我绝对可以使用它们,我想我没有正确理解这个概念。我认为嵌套属性只有在您一次创建或编辑两个模型时才有意义。在我的情况下,用户已经存在,我只需要为该用户创建3个预测并将它们提交到一起。 – jktress
ActiveRecord不应更新现有的用户记录,除非您对其进行更改,所以我认为在您的案例中使用嵌套表单是完全可以接受的。您对现有用户记录的问题和担忧非常敏感。 +1为好思维 –