使用has_many关联的Rails范围

时间:2015-04-01 00:42:57

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord associations

我有三个模型定义如下:

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的范围称为“有效”&#39;选择具有类型1限制的孩子。我想在父母中添加一个类似的范围,选择父母可以限制第一类或有效的孩子(即限制类型1的孩子)。

我如何创建这样的范围?

1 个答案:

答案 0 :(得分:0)

看起来您需要做的就是返回父母限制或孩子限制为1的唯一父母。

我建议使用rails console rails c来测试和优化范围。

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