Filing multiple entries without nesting

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.

+4
source share
1 answer

I think the very first element, a nested route, may not be the approach you are looking for. This can tie you to 1 new record of model prediction in the form.

You really want accepts_nested_attributes_for in your model. With this set, use form_for (and simple_form_for, if possible, using a simple_form gem). Then with code like form_for @user do | f | use f.fields_for: forecast

Ways to save the user controller will also automatically check and save nested entries.

As you may know, Ryan Bates has excellent railscasts for this.

+2
source

Source: https://habr.com/ru/post/1368871/


All Articles