Search code examples
ruby-on-railsrubyundefinedscaffoldrails-generate

Calling created Objects in Rails Scaffold


I am new to Rails and creating a football results app, I did a rails generate Scaffold Team name:string form:string then I added a few teams to the table, my next step I tried was to create a Fixtures table that stores teams, so I did rails generate Scaffold Fixture week:string homeTeam:team awayTeam:team homeScore:integer awayScore:integer when I tried to update the database doing a rake db:migrate I am getting an error undefined method:team I understand rails does not like the way I specify them teams as type team.

How can I go about getting this to work, as when creating a fixture I want to be able to choose from a list of teams already stored in a teams table?


Solution

  • As a random aside, the convention in ruby/rails is to use underscores as opposed to camelCase for variables and methods.

    On to your actual question! You need to setup relationships yourself in the generated Team and Fixture models. Scaffolding can help you setup the relationships though by getting the correct foreign keys in place.

    For the Fixture scaffold, generate it like this:

    rails g scaffold fixture week:string home_team_id:integer away_team_id:integer home_score:integer away_score:integer
    

    Note that g is a shortcut for generator and the generator doesn't need anything to be capitalized.

    Now, in your Team model you'll want to define your relationship to the Fixture and vice versa (I'm no sports expert, but wouldn't naming it Game make more sense?):

    class Team < ActiveRecord::Base
        has_many :home_games, :class_name => Fixture, :foreign_key => :home_team_id
        has_many :away_games, :class_name => Fixture, :foreign_key => :away_team_id
    end
    
    class Fixture < ActiveRecord::Base
        belongs_to :home_team, :class_name => Team
        belongs_to :away_team, :class_name => Team
    end