开发者

Multiple has_many relationships to the same class

开发者 https://www.devze.com 2023-04-03 07:12 出处:网络
I\'m building a football game and I\'m having trouble creating Club and Match classes. I want to be able to do this:

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::St开发者_运维问答atementInvalid: 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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消