【发布时间】:2017-02-10 08:50:39
【问题描述】:
所以我对 ActiveRecord 是如何处理这个问题感到困惑,希望有人能给我一些见解。
我有一个具有多态关系的表。我们将其称为表选择。在那里我定义了:
belongs_to :chooseable, polymorphic: true
我有两个模型,我们叫一个电影,另一个戏剧。在那里,我有:has_many :choices as: chooseable, dependent: destroy
在具有多态关系的模型中,我有两个作用域:
scope :with_movies, -> {
includes(:movies)
.where("chooseable_type": "Measure")
}
scope :with_shows, -> {
includes(:shows)
.where(shows: { hidden: false })
}
让我感到困惑的是,如果我说 users.choices.with_movies,而我忽略了 chooseable_type where 条件,AR 会拒绝我并说:
Unknown column 'choices.chooseable_type' in 'where clause': SELECT `movies`.* FROM `movies` WHERE `choices`.`chooseable_type` = 'Movie' AND `movies`.`id` IN (728)
然而,在第二个范围 with_shows 中,我不需要定义 chooseable_type - 它工作正常。更令人困惑的是,如果我删除 where 子句,with_shows 也不起作用。
我真的不明白为什么第二个作用域中的 where 子句允许生成正确的查询,但没有它,它就会落空。
【问题讨论】:
标签: mysql ruby-on-rails ruby activerecord