I am sure that I have already thought about this problem, but I canβt understand how easy it is to create and send multiple records at once. I have a User model and a Prediction model. The user has_many predictions, and Prediction belongs to the user. I have nested routes this way
:resources users do :resources predictions end
When I visit users / 1 / predictions / new, I need to create 6 forecast records and immediately send them to db.
In my forecast 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 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 sends only one record instead of 3. I thought I might have to use: accepts_nested_attributes_for, however I do not need to create and update user models at the same time. Existing users will create forecasts 3 at a time for several Races, as this application is for imagination.