我有一个模型,其中多态参考了另外两个模型。我在本文eager load polymorphic中也包含了不同的引用,因此我仍然可以在.where
子句中进行特定于模型的查询。我的查询工作正常,因此我可以搜索执行Score.where(athlete: {foo})
的乐谱,但是,当我尝试执行.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
谢谢!
@ blazpie,使用您的范围建议对我有用。
“那些范围限定的belongs_to可以很容易地用分数:scope :for_teams, -> { where(scorable_type: 'Team') }
]中的范围替换