我有 3 个 Ruby on Rails 表:用户、组和帖子(加上用于 has_and_belongs_to_many 的联接表“groups_users”)......
以下是相关的表定义:
create_table "posts", force: true do |t|
t.integer "user_id"
t.integer "group_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "groups", force: true do |t|
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", force: true do |t|
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "groups_users", id: false, force: true do |t|
t.integer "user_id", null: false
t.integer "group_id", null: false
end
以及模型:
Group Model:
has_and_belongs_to_many :users, dependent: :destroy
has_many :posts, inverse_of: :group, dependent: :destroy
User Model:
has_many :posts, inverse_of: :user, dependent: :destroy
has_and_belongs_to_many :groups, dependent: :destroy
has_many :groupposts, through: :groups, source: :posts, class_name: "Post"
Post Model:
belongs_to :group, inverse_of: :posts
belongs_to :user, inverse_of: :posts
帖子的群组可能为空,因此用户可以在没有任何群组的情况下发布一般帖子 (group_id == nil),或者他们可以在他们所属的群组之一内发布帖子。
我试图弄清楚是否有一个事件记录查询可以给我: (1) 来自任何用户的所有一般帖子(无 group_id),加上 (2) 用户所属的任何群组的所有帖子。
所以类似:
Post.where(:group_id => nil)
独特地加入:
@user.groupposts
我认为它是在附近的东西:
Post.includes(:groups [:users]).where("(posts.group_id IS NULL) OR (posts.groups.users CONTAINS ?)", @user.id) # THIS IS NOT CORRECT, THE SECOND HALF OF THE 'OR' STATEMENT IS GARBAGE
最佳答案
您不能在同一个查询中得到该结果(如果您使用 UNION
编写完整的查询,则可以得到它),因为您的条件应用于同一字段,您应该有 2 个不同的结果查询它。
对于一般帖子,您可以尝试使用此方法
Post.where("group_id is null")
#or in scope
scope :general_posts, lambda { where ("group_id is null") }
来自用户组的所有帖子
Post.where( group_id: User.uniq.pluck(:id) )
#scope
scope :user_groups, lambda { where( group_id: User.uniq.pluck(:id) ) }
希望对您有帮助
关于mysql - 用于连接 has_and_belongs_to_many 关系的 ActiveRecord 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27934816/