Rails query / scope: exclude objects according to the merged model attribute

My models look like this:

class Ticket < ActiveRecord::Base has_and_belongs_to_many :tags end class Tag < ActiveRecord::Base has_and_belongs_to_many :tickets end 

I want to have an area that gives me all the different Tickets that are not marked unresolved (as in tag.name != "unresolved" )

How can I do it? For example, if 1 ticket has 6 tags (one of which is unresolved ), I want to return only one copy of this ticket, and not 5 in the field. I managed to do the opposite (all Tickets marked with unresolved tags) as such:

 scope :unresolved, :select => "DISTINCT tickets.*", :joins => :tags, :conditions => "tags.name = 'unresolved'" 
+4
source share
1 answer

Depending on how flexible you want to chain, you have two options.

  • Use uniq within the scope (note: this can negatively affect the binding of this scope to others, especially when adding more complex conditional expressions):

    scope :unresolved, -> { joins(:tags).where(tags: { name: 'unresolved' }).uniq }

  • Use LEFT OUTER to connect via includes(:tags) instead of the INNER connection used by default joins(:tags)

    scope :unresolved, -> { includes(:tags).where(tags: { name: 'unresolved' }) }

0
source

Source: https://habr.com/ru/post/1385274/


All Articles