【问题标题】:Hard time creating a class scope for HABTM relation很难为 HABTM 关系创建类范围
【发布时间】:2014-04-17 10:00:20
【问题描述】:

这是我的简化情况:

class Producer
  has_and_belongs_to_many :rules
end

class Rule
  has_and_belongs_to_many :producers
end

但是Rule 恰好遵循 STI 结构。所以我有这个:

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

没什么大不了的,效果很好。所以现在我想创建一个只返回与ProductRules 相关的Producers 的范围

类似的东西:

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

谁能指出一个快速的解决方案?

注意:我显然不想加载所有生产者并在之后选择它们,我只想直接加载正确的生产者


更新

我使用的是 Rails 2.3.15 版

【问题讨论】:

    标签: ruby-on-rails has-and-belongs-to-many scopes


    【解决方案1】:

    Producer 和Rule 的子类之一之间的每个关联都将在连接表上创建一个单独的记录。您可以使用该事实并选择在连接表上有任何记录指向它们的所有Producers(注意选择正确的type):

    在 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多