Frage

This is my simplified situation:

class Producer
  has_and_belongs_to_many :rules
end

class Rule
  has_and_belongs_to_many :producers
end

But Rule happens to follow a STI structure. So I have this:

class Producer
  has_and_belongs_to_many :rules

  has_and_belongs_to_many :product_rules, join_table: :producers_rules,
    association_foreign_key: :rule_id

  has_and_belongs_to_many :fee_rules, join_table: :producers_rules
    association_foreign_key: :rule_id
end

class Rule
  has_and_belongs_to_many :producers
end

class ProductRule < Rule
end

class FeeRule < Rule
end

No big deal, works out just fine. So now I want to create a scope that returns only Producers that are related to ProductRules

Something equivalent to this:

Producer.all.select{|x| x.product_rules.any? }

Can anyone point out a quick solution?

NOTE: I obvioulsy don't want to load all producers and select them afterward, I want to directly load only the right ones


UPDATE

Im using Rails version 2.3.15

War es hilfreich?

Lösung

Every association between Producer and one of Rule's subclasses is going to create a separate record on the join table. You can use that fact and select all the Producers that have any record on the join table pointing to them (taking care to select the correct type):

In Rails 2.x:

class Producer
  def self.with_some_product_rule
    scoped(conditions: <<-SQL)
      producers.id IN (
        SELECT producer_id FROM producers_rules
        INNER JOIN rules ON rules.id = producers_rules.rule_id
        WHERE rules.type = 'ProductRule'
      )
    SQL
  end
end
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top