Multiple record submit without nesting
I'm sure I'm over thinking this problem, but I can't seem figure out how to simply create and submit multiple records at once. I have a User model and a Prediction model. User has_many predictions, and a Prediction belongs_to a user. I've nested my routes like so
:resources users do
:resources predictions
end
when I visit users/1/predictions/new, I need to create 6 Prediction records, and submit them at once to the db.
In my Predictions controller:
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开发者_如何学JAVA 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
And in my Prediction 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 %>
This shows and submits only one record instead of 3. I thought I might have to use :accepts_nested_attributes_for, however I don't need to create and update User models at the same time. Existing Users will be creating predictions 3 records at a time for several Races, as this is a fantasy sports app.
I think that the very first item, the nested route may not be the approach you are looking for. That may tie you down to 1 new model prediction record on the form.
You do indeed want accepts_nested_attributes_for
in your model. With that set use a form_for (and simple_form_for if possible, using the simple_form gem). Then with code like
form_for @user do |f|
use f.fields_for :prediction
The user controller save methods will also validate and save the nested records automatically.
As you may know Ryan Bates has great railscasts for this.
精彩评论