查找没有has_many的记录:通过记录匹配条件

时间:2016-07-11 11:45:09

标签: ruby-on-rails activerecord rails-activerecord has-many-through

使用Rails 4,并给出以下模型:

class Draft < ActiveRecord::Base
  has_many :drafters
  has_many :users, through: :drafters
end

class Drafter < ActiveRecord::Base
  belongs_to :draft
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :drafters
  has_many :drafts, through: :drafters
end

如何检索与用户实例current_user无关的所有草稿?也就是说,没有Drafter属于dd的所有草稿current_user

如果有帮助,我可以使用Squeel

4 个答案:

答案 0 :(得分:1)

您可以使用includes

来实现它
Draft.includes(:drafters)
     .where('(drafters.user_id <> ? or drafters.user_id is null)', current_user.id})
     .references(:drafters)

答案 1 :(得分:1)

使用Squeel,您可以:

Draft.joins{drafters.outer}.where{(drafters.user_id != current_user.id) | (drafters.user_id.eq nil)}

将生成:

SELECT "drafts".* FROM "drafts" LEFT OUTER JOIN "drafters" ON "drafters"."draft_id" = "drafts"."id" WHERE ("drafters"."user_id" != 1 OR "drafters"."user_id" IS NULL)

答案 2 :(得分:0)

Draft.includes(:drafters).where(:drafters => { :draft_id => nil } ) 

将返回所有没有起草人的草稿。

Draft.includes(:drafters).where.not(:drafter => { user_id => current_user.od })

将返回所有不属于current_user的草稿。

有关详细信息,请查看the difference between outer an inner join

答案 3 :(得分:0)

我找到了一个基于以下嵌套查询的答案(带有吱吱声):

{ = Formula [Bookmark ] [\#Numeric Picture ] }

可以转换为Rails + squeel查询:

SELECT "drafts"."id" FROM "drafts"
    WHERE "drafts"."id" NOT IN 
        (SELECT "drafters"."draft_id" FROM "drafters" 
            WHERE (("drafters"."draft_id" = "drafters"."id" 
                    AND "drafters"."user_id" = 2)))