ruby - Rails scope using has_many association -


i have 3 models defined below:

class parent < activerecord::base   has_many :kids   has_many :restrictions    def has_valid_restriction?     self.restrictions.where(:type => 1).size > 0   end end  class kid < activerecord::base   belongs_to :parent   has_many :restrictions    scope :valid, -> {     includes(:restrictions).where("restriction.type = 1")   } end  class restriction < activerecord::base   belongs_to :restricted_object #this can kid or parent end 

kid has scope called 'valid' chooses kids having restriction type 1. want add similar scope parent chooses parents either have restriction of type 1 or valid kid (i.e. kid restriction of type 1).

how can create such scope?

it looks need return unique parents either parent restriction or kid restriction 1.

i recommend using rails console rails c test , refine scopes.

scope :valid, -> {   joins(:restrictions, kids: :restrictions).where("parents.restrictions = 1 or kids.restrictions = 1).uniq } 

Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -