首页 > 解决方案 > Rails 5:当多态引用也带有不同的关联时如何允许模型创建

问题描述

我的模型具有对其他两个模型的多态引用。根据这篇文章,我还包含了不同的引用,急切加载多态,因此我仍然可以在我的.where子句中执行特定于模型的查询。我的查询工作,所以我可以搜索分数Score.where(athlete: {foo}),但是,当我尝试做 a 时.create,我得到一个错误,因为在验证期间,不同的引用别名似乎使我的多态引用的 Rails 蒙蔽了。

鉴于运动员可以单独参加比赛,也可以作为团队的一员参加比赛:

class Athlete < ApplicationRecord
  has_many :scores, as: :scoreable, dependent: :destroy
end

class Team < ApplicationRecord
  has_many :scores, as: :scoreable, dependent: :destroy
end

class Score < ApplicationRecord
 belongs_to :scoreable, polymorphic: true

 belongs_to :athlete, -> { where(scores: {scoreable_type: 'Athlete'}) }, foreign_key: 'scoreable_id'

 belongs_to :team, -> { where(scores: {scoreable_type: 'Team'}) }, foreign_key: 'scoreable_id'

  def athlete
    return unless scoreable_type == "Athlete"
    super
  end

  def team
    return unless scoreable_type == "Team"
    super
  end
end

当我尝试这样做时:

Athlete.first.scores.create(score: 5)

...或者...

Score.create(score: 5, scoreable_id: Athlete.first.id, scoreable_type: "Athlete")

我得到错误:

ActiveRecord::StatementInvalid (SQLite3::SQLException: no such column: scores.scoreable_type

谢谢!

标签: ruby-on-railsruby-on-rails-5rails-activerecordpolymorphic-associations

解决方案


@blazpie,使用您的范围界定建议对我有用。

“那些范围内的 belongs_to 可以很容易地被 Score 中的范围替换:scope :for_teams, -> { where(scorable_type: 'Team') }


推荐阅读