【发布时间】:2016-07-12 17:45:25
【问题描述】:
TLDR:我无法让 where 子句在嵌套(嵌套的 1 或 2 层)has_many 关联中工作
#Author.rb
has_many :posts
#Post.rb
belongs_to :author
has_one :post_setting
#PostSetting.rb
#Has attributes like draft (bool), flagged(bool), etc.
belongs_to :post
现在,如果我尝试在 Author 中创建一个关联,以查找 post_setting.draft = false 的所有帖子,例如,如下所示。
has_many :published_posts,
-> {
includes(:post_setting)
.where(post_setting: {draft: false})
.distinct
},
class_name "Post"
不幸的是,失败并出现以下错误
PG::UndefinedTable: ERROR: missing FROM-clause entry for table "post_setting"
或者,我也希望能够执行以下操作 -
#Group.rb
has_many :authors
has_many :posts,
-> {
includes(:post_setting)
.where(post_setting: {draft: false})
.distinct
},
through: authors
总的来说,我觉得关于 where/joins/includes 如何在关联中工作的规则不是很清楚。在帖子上创建一个范围是否比在作者的has_many 中包含范围更可取?
谢谢!
PS。我正在使用 Rails 4.2.5。
【问题讨论】:
标签: ruby-on-rails activerecord