我的模型是这样的:
class Ticket < ActiveRecord::Base
has_and_belongs_to_many :tags
end
class Tag < ActiveRecord::Base
has_and_belongs_to_many :tickets
end
我想要一个范围,为我提供所有未标记为 unresolved
的不同 Tickets
(如 tag.name != "unresolved"
)
我该怎么做呢?例如,如果一张票有 6 个标签(其中一个是 unresolved
),我只想返回该票的 1 个实例,而不是范围内的 5 个。我设法做了相反的事情(所有 Tickets
标记为 unresolved
):
scope :unresolved, :select => "DISTINCT tickets.*", :joins => :tags, :conditions => "tags.name = 'unresolved'"
最佳答案
根据您希望范围链接的灵 active ,您有两种选择。
使用
uniq
在范围内(注意:这可能会对将此范围与其他范围链接产生负面影响,尤其是在添加更复杂的条件时):scope :unresolved, -> { joins(:tags).where(tags: { name: 'unresolved' }).uniq }
通过
includes(:tags)
使用 LEFT OUTER 连接而不是joins(:tags)
使用的默认 INNER 连接scope :unresolved, -> { includes(:tags).where(tags: { name: 'unresolved' }) }
关于mysql - Rails 查询/范围 : exclude objects according to attribute of joined model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8425779/