0

我有如下定义的三种型号:的Rails应用范围的has_many协会

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 

孩子有一个名为“有效”范围,其选择具有与1型限制孩子我想类似的范围增加家长选择有一种限制类型或有效孩子(即限制类型1的孩子)的父母。

如何创建这样一个范围?

回答

0

它看起来像所有你需要做的是返回唯一的父母在那里无论是父母限制或孩子限制为1

我建议使用导轨控制台rails c试验和改进范围。

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