ActiveRecord查询用于加入has_and_belongs_to_many关系

时间:2015-01-14 02:16:16

标签: mysql ruby-on-rails ruby activerecord

我有3个Ruby on Rails表:用户,组和帖子(加上一个连接表" groups_users"用于has_and_belongs_to_many).....

以下是相关的表格定义:

  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),或者他们可以在他们所属的群组中制作帖子。

我试图弄清楚是否有一个Active Record Query会给我: (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

1 个答案:

答案 0 :(得分:0)

您不能在同一个查询中获得该结果(如果您使用UNION编写完整查询,则可以拥有该结果),因为您的条件适用于同一个字段,您应该有2个不同的查询

对于General Post,您可以尝试使用此

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) ) }

希望这可以帮到你