Search code examples
ruby-on-railsrubynested-forms

Rails: Nested form not creating record


I am trying to build a form to create a game that has four different instances of players. I have built a nested form that renders four sets of player fields to the game form. However, nothing happens when I submit the form. I would like the submission of the form to call upon the #create action of my controller but it does not even call create (I try to raise an error in #create but cannot).

Here is my code:

game.rb

class Game < ApplicationRecord
  has_many :players, dependent: :destroy
  has_many :rounds, dependent: :destroy

  accepts_nested_attributes_for :players
end

player.rb

class Player < ApplicationRecord
  belongs_to :game
  has_many :rounds
  validates :name, presence: true, length: { maximum: 15 }


end

games_controller.rb

class GamesController < ApplicationController

  def create
    raise
    @new_game = Game.new(game_params)
    @new_game.start = Date.today
    @new_game.save!
    redirect_to root_url
  end

  def new
     @game = Game.new
     4.times { @game.players.build }
   end

   private
     def set_game
       @game = Game.find(params[:id])
     end

     def game_params
       params.require(:game).permit(:date, player_attributes: [:name])
     end
end

views/games/new.rb

<%= form_with model: @game do |f| %>
  Players:
  <ul>
    <%= f.fields_for :players do |players_form| %>
      <li>
        <%= players_form.label :name %>
        <%= players_form.text_field :name %>
      </li>
    <% end %>
  <%= f.submit "Submit"%>
  </ul>
<% end %>

routes.rb

Rails.application.routes.draw do
  root to: 'pages#home'
  resources :games, only: [:create, :new]
end

Here are the logs when I submit the form:

Started POST "/games" for ::1 at 2020-01-15 12:54:13 +0100
Processing by GamesController#create as JS
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"owiE4RViIsVonr9dwDAlLZR8MtZ/EnY/VTUq7o5zxHc2KcQ0Nliag9XnDHQZ7xKc5cIqOwQbuoPwSgkWPMknSA==", "game"=>{"players_attributes"=>{"0"=>{"name"=>"Bob"}, "1"=>{"name"=>"Joe"}, "2"=>{"name"=>"Alice"}, "3"=>{"name"=>"Fernand"}}}, "commit"=>"Submit"}
Completed 500 Internal Server Error in 7ms (ActiveRecord: 0.0ms)



RuntimeError ():

app/controllers/games_controller.rb:4:in `create'

This is my first time asking a question on stackoverflow so please let me know if I am not clear enough/need to give more information.

Thank you!


Solution

  • Based on your log, your form is submitted as JS.
    Just set local to true to disable this:

    views/games/new.rb
    <%= form_with model: @game, local: true do |f| %>
    

    reference: form_with