Multiple has_many relationships to the same class

感情迁移 提交于 2019-12-23 04:24:29

问题


I'm building a football game and I'm having trouble creating Club and Match classes. I want to be able to do this:

match = Match.find(2)
match.home_club = <some club here>
match.away_club = <other club here>

And also this:

club = Club.find(2)
club.matches # Returns all matches where club plays home or away

This is what I have now:

class Club < ActiveRecord::Base
  has_many :matches
end

class Match < ActiveRecord::Base
  belongs_to :home_club, :class_name => "Club"
  belongs_to :away_club, :class_name => "Club"
end

But when I try to do Club.first.matches, I get this error:

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: matches.club_id: SELECT "matches".* FROM "matches" WHERE ("matches".club_id = 1)

I have played around with :inverse_of but I didn't get it working. Is it even possible like this, or do I need to have two separate :has_many relationships in Club? Like this:

class Club < ActiveRecord::Base
  has_many :home_matches, :class_name => "Match"
  has_many :away_matches, :class_name => "Match"
end

I tried this too, but it didn't work either.


回答1:


You are building a many-to-many relationship, so you'll need a link table. Rather then having foreign keys in either of your entity tables, this table stores those relationships, and should have nothing but a match_id and a club_id to associate the two tables. You can then use

class Club < ActiveRecord::Base
    has_many :matches, :through => :matches_clubs
end

etc.

See more here http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html




回答2:


Did you define the relation in your schema as home_club_id and away_club_id? Because it seems rails is trying to get match.club_id which clearly conflicts with the model you require

I think your model is wrong and should be revised. Clubs should not have a match_id.

Match should be:

  • home_club_id
  • away_club_id
  • time
  • score

Club should be:

  • name
  • city

I think if you remove the belongs to from clubs you should be fine.

If you want to be able to do club.matches. You might have to write a custom sql query that looks in both the home_club and away_club columns. Or make a relation table for clubs -> match that has a extra metafield saying if the club was home or away. While you have the home and away clubs in your match table



来源:https://stackoverflow.com/questions/7310909/multiple-has-many-relationships-to-the-same-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!