4

我敢肯定我在想这个问题,但我似乎无法弄清楚如何简单地创建和提交一次多个记录。我有一个用户模型和一个预测模型。用户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条记录,用于多场比赛,因为这是一款梦幻体育应用。

+0

为什么你不想使用嵌套窗体?看起来他们完全适合你的问题。 –

+0

我绝对可以使用它们,我想我没有正确理解这个概念。我认为嵌套属性只有在您一次创建或编辑两个模型时才有意义。在我的情况下,用户已经存在,我只需要为该用户创建3个预测并将它们提交到一起。 – jktress

+0

ActiveRecord不应更新现有的用户记录,除非您对其进行更改,所以我认为在您的案例中使用嵌套表单是完全可以接受的。您对现有用户记录的问题和担忧非常敏感。 +1为好思维 –

回答

2

我认为,第一个项目,嵌套的路线可能不是你正在寻找的方法。这可能会将您与表格上的1个新模型预测记录绑定。

您确实需要在您的模型中使用accepts_nested_attributes_for。使用该设置使用form_for(如果可能,请使用simple_form_for,使用simple_form宝石)。然后用代码 form_for @user do | f | 使用f.fields_for:预测

用户控制器保存方法也将自动验证并保存嵌套记录。

正如你可能知道的,瑞恩贝茨对此很棒railscasts