多个的has_many关系以相同的类 [英] Multiple has_many relationships to the same class

查看:140
本文介绍了多个的has_many关系以相同的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要建一个足球比赛,我在创建俱乐部和比赛类的麻烦。我希望能够做到这一点:

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>

和也这样的:

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

这是我现在有:

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

但是,当我尝试做 Club.first.matches ,我得到这个错误:

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)

我打周围的:inverse_of ,但我没有得到它的工作。它甚至有可能是这样,或者我需要有两个独立的:在俱乐部的has_many 的关系?像这样的:

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.

推荐答案

你定义模式中的关系为 home_club_id away_club_id ?因为它似乎Rails是试图让 match.club_id 这显然与您需要的模式冲突

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

我觉得你的模式是错误的,应予以修订。 俱乐部不应该有一个 match_id

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

匹配应该是:

  • home_club_id
  • away_club_id
  • 时间
  • 分数

俱乐部应该是:

  • 名称
  • 城市

我想,如果你删除了属于从俱乐部你应该罚款。

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

。 您可能需要编写自定义的SQL查询,看起来在这两个home_club和away_club列。还是做一个关系表的俱乐部 - >匹配,有一个额外的metafield说,如果俱乐部是居家或外出。当你有主客场俱乐部在您的匹配表

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

这篇关于多个的has_many关系以相同的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆