SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Thread: has_one()

Hybrid View

  1. #1
    SitePoint Addict JNKlein's Avatar
    Join Date
    Sep 2004
    Location
    New York, NY
    Posts
    258
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    has_one()

    I can't figure this out...

    this is the strangest error...

    There is a Game with a Home and Away Team. The game table has hometeam_id and awayteam_id as foreign keys to the team table's id.

    game model
    Code:
    class Game < ActiveRecord::Base
      has_one :hometeam, :class_name => 'Team', :foreign_key => 'hometeam_id'
      has_one :awayteam, :class_name => 'Team', :foreign_key => 'awayteam_id'
    end
    and in the view
    Code:
    <%= game.awayteam.class %>
    And this gets me:
    Code:
    #42S22Unknown column 'teams.awayteam_id' in 'where clause': SELECT * FROM teams ... etc
    Why is it looking for awayteam_id in teams and not in games? Am I using has_one incorrectly?

  2. #2
    SitePoint Guru
    Join Date
    Aug 2005
    Posts
    986
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Use belongs_to. Has_one looks in the foreign table, just like has_many.

  3. #3
    SitePoint Guru silver trophy Luke Redpath's Avatar
    Join Date
    Mar 2003
    Location
    London
    Posts
    794
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    And you'll probably want a has_many :games on the Team side, too.

    Remember this...if you have has_one/many on one side of the association, you'll usually want a belongs_to on the other side.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •