Search code examples
ruby-on-railsformspartial-viewsnomethoderror

NoMethodError in my Teams#Show


For some reason I get an error on this line. Everything seems to be correct.

undefined method `datetime' for #<Game:0x87e73f0> 

Screenshot of console log: www.gyazo.com/0947c493218a3fecdb5849e1e13f181a

app/views/games/_form.html.erb where line #4 raised

<%= f.text_field :datetime %>

Migration file:

class CreateGames < ActiveRecord::Migration
  def change
    create_table :games do |t|
      t.string :datetime
      t.string :location
      t.references :team, index: true

      t.timestamps null: false
    end
  end
end

Partial Form:

<%= form_for([@team, @team.games.build]) do |f| %>
    <p>
        <%= f.label :datetime %><br>
        <%= f.text_field :datetime %>
    </p>

    <p>
        <%= f.label :location %><br>
        <%= f.text_field :location %>
    </p>

    <br>

    <p>
        <%= f.submit %>
    </p>
<% end %>

Routes file:

Rails.application.routes.draw do

  devise_for :users
  resources :teams do
    resources :members
  end

  resources :teams do
    resources :games
  end

  root "teams#index"
end

Solution

  • I don't like the idea that you've called a column "datetime" - if it's not protected, it's definitely misleading (considering most SQL flavours have a datetime column type).

    Apart from it appearing that you're calling the wrong column name:

    Game.column_names I got: => ["id", "date_time", "location", "team_id", "created_at", "updated_at"]
    

    You need to reference date_time:

     <%= f.label :date_time %><br>
     <%= f.text_field :date_time %>
    

    ... you'd be much better changing the name of the attribute in the database:

    $ rails g migration ChangeDateTime
    
    #db/migrate/change_date_time____.rb
    class ChangeDateTime < ActiveRecord::Migration
       def change
         rename_column :games, :date_time, :start_time
       end
    end
    
    $ rake db:migrate
    

    This will allow you to reference start_time, and should not conflict with your SQL installation in any way.