查找记录的关联属性的NONE是否具有给定值的记录

时间:2015-09-07 14:57:42

标签: ruby-on-rails ruby-on-rails-4 activerecord

class Project
      has_many :quotes
      scope :available, ->(business_id) { joins(:quotes).where.not(quotes: { business_id: business_id }) }
      scope :active, ->(business_id) { joins(:quotes).where(quotes: { business_id: business_id }) }
end

class Quote
      belongs_to :project
end

嗨,我正在尝试定义一个available范围,该范围会返回Project个记录的关系,这些记录对于给定的{{1}不具有Quote }}。我尝试使用上面的范围,但它返回一个空关系?

类似的business_id范围似乎工作正常。这里唯一的区别是active子句。

有什么想法吗?我是否必须为此编写原始SQL?

1 个答案:

答案 0 :(得分:2)

应该这样做。

  scope :available, ->(business_id) {where.not(Quote.where("quotes.project_id = projects.id and quotes.business_id = ?", business_id).exists)}