Rails查询以显示current_user没有评论的所有帖子

时间:2017-11-17 19:43:10

标签: ruby-on-rails postgresql activerecord ruby-on-rails-5 where

我有一个应用程序,我需要查看当前用户没有引号的所有请求。我希望看到没有引号的请求和其他用户引用的请求。

对于我一直在使用的引号:

Request.includes(:quotes).where( quotes: { id: nil } ).order(created_at: :desc)

以及我正在使用的Where Not查询:

Requests.joins(:quotes).where.not(quotes: { service_center_id: current_service_center.id })

这适用于一个引用。如果我引用请求,请求不再在列表中,但只要其他人引用它就会返回到我的列表中。好像查询看到其他引号不是我所以如果显示请求,即使我也引用了。

这是一个关于Thoughtbot博客的链接,在那里没有激发我去研究模型的灵感。在底部,他做同样的查询。我已通过电子邮件发送作者但尚未回复。 https://robots.thoughtbot.com/activerecords-wherenot

以下是我的模特:

用户

devise :database_authenticatable, :registerable,
       :recoverable, :rememberable, :trackable, :validatable

validates :first_name,  presence: true  
alidates :last_name,   presence: true  
validates :zipcode,     presence: true  


has_many :autos  
has_many :requests  
has_many :quotes, through: :requests  
has_many :appointments, through: :quotes 

请求

belongs_to :user  
belongs_to :auto  
has_many :quotes, dependent: :destroy  
has_many :appointments, through: :quotes  

validates :service, presence: true  

serialize :service

validates_associated :quotes

引用

belongs_to :request  
belongs_to :service_center  

Service_center

devise :database_authenticatable, :registerable,
       :recoverable, :rememberable, :trackable, :validatable  

has_many :quotes  
has_many :requests, through: :quotes  

1 个答案:

答案 0 :(得分:0)

以下是实现三个目标的方法。

没有引号的请求:

Request.includes(:quotes).where( quotes: { id: nil } ).order(created_at: :desc)

来自其他服务中心的报价请求:

Requests.joins(:quotes).where.not(quotes: { service_center_id: current_service_center.id })

以下是您的问题的答案:

您的服务中心没有报价的请求:

Request.where.not(
  id: Request.joins(:quotes)
        .where(quotes: { service_center_id: current_service_center.id })
        .select(:id) 
)

这有些笨拙,但应该有效。子查询获取具有当前服务中心报价的所有请求。外部查询返回不在第一个列表中的所有请求。它应该仍然可以在数据库中使用一个查询快速运行。

另一种产生相同结果的解决方案是使用NOT EXISTS

Request.joins(:quotes).where(
  Quote
    .where('requests.id = quotes.request_id')
    .where('quotes.service_center_id = ? ', current_service_center.id)
    .exists.not
)

这将在SQL中生成NOT EXISTS子查询。它应该导致与其他查询大致相同的性能。我想这只是一个偏好问题。

相关问题