用户有很多帖子。
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/