mardi 31 mars 2015

Rails scope using has_many association

I have three models defined as 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 be kid or parent
end


Kid has a scope called 'valid' which chooses the Kids having a restriction with type 1. I want to add a similar scope to Parent which chooses Parents which either have a restriction of type one or a valid Kid (i.e. a Kid with restriction of type 1).


How can I create such a scope?


Aucun commentaire:

Enregistrer un commentaire