ruby-on-rails - 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
谢谢!
解决方案
@blazpie,使用您的范围界定建议对我有用。
“那些范围内的 belongs_to 可以很容易地被 Score 中的范围替换:scope :for_teams, -> { where(scorable_type: 'Team') }
推荐阅读
- string - 如何在 Amazon Quicksight 中聚合字符串
- pointers - pic33 指向位对象的指针
- typescript - TypeScript 任何不提供特定参数的类型
- java - 文件夹删除后的 AccessDeniedException
- azure-log-analytics - Azure Sentinel ThreatIntelligence 重复数据
- angular - Angular Form RxJS 在一个表单输入上进行多重过滤
- javascript - 基石 BigCommerce 复选框未选中
- mongodb - 如何使用 PyMongo lib 查询 Azure MongoDB 文档
- google-bigquery - BigQuery 查询返回对象 ID 相同的所有数组的不同数组联合
- ode - 使用 deSolve 时,如何将初始条件强制到离散化 PDE 上?