Mathew
Mathew

Reputation: 19

Make form for model and model that belongs to it

I want to have form for model Event and form for Game model which belongs to Event on single page. Problem is that I want to have single button for submit which would save Event and next Game which belongs to Event. How such form and controllers would look like?

Upvotes: 0

Views: 89

Answers (1)

Ryan K
Ryan K

Reputation: 4053

Inside your form_for, you can use the method fields_for, like this:

<%= form_for @event do |f| %>
  #put your @event fields here
  <%= f.fields_for :games, @game do |g| %>
    #put your @game fields here, though you can also have the @event fields here too
  <% end %>
<% end %>

In your Event model, add accepts_nested_attributes_for :games somewhere after your has_many :games line.

In your EventController, you need to add the game params to your strong params method:

params.require(:event).permit(:name, :time, :something_else,
                              games_attributes: [:score, :length, :whatever])

Upvotes: 1

Related Questions