【问题标题】:Filter for parent objects with at least one child within a scope过滤范围内至少有一个子对象的父对象
【发布时间】:2015-09-23 15:51:24
【问题描述】:

我想用属于范围一部分的书籍返回用户 -

class User < ActiveRecord::Base
  has_many :books
end

class Book < ActiveRecord::Base
  belongs_to :user

  scope :published, -> { where (status: 'Published') }
end

所以

Book.published

返回所有已出版的书籍。我正在尝试定义拥有一本或多本已出版书籍的所有用户的范围。

知道

User.joins(:books).uniq.all

返回所有用户一本书(来自Rails: How to get objects with at least one child?) - 我可以添加一个范围,还是有更好的方法?

【问题讨论】:

  • 所以你希望所有有孩子的父母都在attends_club范围内?

标签: ruby-on-rails postgresql activerecord


【解决方案1】:

首先,模型类名应该是单数 em> 如果我理解正确,您希望所有用户都在published 范围内拥有一本书,那么我会将scope 放在User 模型中,并稍作更改,如下所示

class User < ActiveRecord::Base
  has_many :books
  scope :published, -> { joins(:books).where(books: { status: 'Published' }) }
end

现在您可以执行User.published,它会返回所有用户的图书状态为已发布

【讨论】:

  • 我现在正在处理它 - 我目前收到错误消息 - ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "child" - 谷歌搜索得到github上的以下rails问题-github.com/rails/rails/issues/13531#issuecomment-35103068-'正在尝试解决是否相同-您怎么看?
  • @RADan 您的表是否命名为child?或children?
  • 我可以检查一下 -> { joins(children) ... 是类名的复数还是单数?
  • 我试图让类名通用,但我不认为我做了一个好的选择:)
  • @RADan 尝试将self.table_name = "child" 放入Child 模型中看看。
猜你喜欢
  • 2023-03-17
  • 2021-01-10
  • 2014-03-28
  • 2022-11-17
  • 1970-01-01
  • 2013-04-28
  • 1970-01-01
  • 1970-01-01
  • 2017-06-06
相关资源
最近更新 更多