【问题标题】:Rails model that includes both a has_many and has_one relationship, relating two models that have a has_many to has_many relationship包含 has_many 和 has_one 关系的 Rails 模型,将两个具有 has_many 到 has_many 关系的模型关联起来
【发布时间】:2017-06-15 16:27:36
【问题描述】:

这是这个问题的一个小扩展:Rails model that has both 'has_one' and 'has_many' but with some contraints

在这里,我试图将两个模型关联起来,每个模型都有多个 -> 我有一个中间模型,它存储外键,允许“通过”关系。具体来说,我正在尝试将比赛和球队联系起来,我希望每个球队都“has_one :current_matchup”

以下是我的模型的相关摘录:

团队:

has_many :matchup_teams
has_many :matchups, through: :matchup_teams

对决:

has_many :matchup_teams
has_many :teams, through: :matchup_teams

MatchupTeam:

belongs_to :matchup
belongs_to :team

我该怎么做? 这是我当前的尝试,但会导致错误:

模型团队:

has_one  :current_matchup_team, -> { where(is_current: true) }, :class_name=> "MatchupTeam"
has_one :current_matchup, through: :current_matchup_team, :class_name=>"Matchup"

【问题讨论】:

    标签: ruby-on-rails activerecord has-many has-one has-one-through


    【解决方案1】:

    如果您使用方法而不是关联来检索 current_matchup,那将是一个更好的方法:

    模型:团队

    def current_matchup
        matchups. where(is_current: true) 
    end
    

    【讨论】:

    • 好的,我很乐意这样做 - 我可以在 eager_load 语句中使用该方法吗?例如 user.teams.includes(:current_matchup) 之类的?
    • 可惜不行,必须是模型关系。
    • ActiveRecord::HasManyThroughSourceAssociationNotFoundError:在模型 LeaguesAndTeams::MatchupTeam 中找不到源关联“current_matchup”或 :current_matchup。试试 'has_many :current_matchup, :through => :current_matchup_team, :source => '。是对战还是团队?
    • 为简洁起见,我删除了上述问题中的命名空间
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多