ruby-on-rails - Rails 加入或包含有条件的 belongs_to

用户有很多帖子。

class User
  has_many :posts
end

帖子属于用户。

class Post
  belongs_to :user
end

我正在尝试查找由管理员用户发布的所有帖子。。 p>

我试过:

Post.where(status: 'published').includes(:user).where(users: { admin: true })

我得到:

PG::AmbiguousColumn: ERROR:  column reference "admin" is ambiguous

最佳答案

您可以将 ActiveRecord::Relation 传递给大多数作用域方法来构建复杂的查询。例如:

Post.where(status: 'published', user: User.where(admin: true)).includes(:user)

这应该生成两个查询;一个将包括具有管理条件的用户的子查询,另一个将加载用户(预先加载)。

请注意,您可以使用范围大大简化这些查询,这使模型负责列的细节:

class User < ApplicationRecord
  scope :admin, -> { where(admin: true) }
end

class Post < ApplicationRecord
  scope :published, -> { where(status: 'published') }
end

# posts from admin users, with eager loaded users
Post.published.where(user: User.admin).includes(:user)

干杯!

https://stackoverflow.com/questions/38380026/

相关文章:

assembly - 汇编中的函数结语

xamarin.forms - 从 Xamarin 的 Picker 中获取选定的值

regex - 如何在 Chrome Dev Tools 中过滤没有扩展的 XHR 请求?

git - 无法解析主机名

google-apps-script - 可以在谷歌脚本中设置一个标题

types - Julia 中的大宽度整数?

apache-camel - 如何在 apache camel 中全局设置交换属性

r - 如何在 R 中绘制阶乘函数

git - 是否可以轻松地将所有提交从一个分支移动到另一个分支作为一个提交?

php - woocommerce rest API 每次调用仅提供 10 个订单