Ruby on rails 为HABTM关系创建类作用域很困难
这是我的简化情况:Ruby on rails 为HABTM关系创建类作用域很困难,ruby-on-rails,has-and-belongs-to-many,scopes,Ruby On Rails,Has And Belongs To Many,Scopes,这是我的简化情况: class Producer has_and_belongs_to_many :rules end class Rule has_and_belongs_to_many :producers end 但是规则恰好遵循STI结构。所以我有这个: class Producer has_and_belongs_to_many :rules has_and_belongs_to_many :product_rules, join_table: :producer
class Producer
has_and_belongs_to_many :rules
end
class Rule
has_and_belongs_to_many :producers
end
但是规则
恰好遵循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
有人能指出一个快速的解决方案吗
注意:我显然不想加载所有的制作人并在之后选择它们,我只想直接加载正确的制作人
更新
Im使用Rails 2.3.15版在
生产者
和规则
的子类之间的每个关联都将在联接表上创建一个单独的记录。您可以使用该事实并选择所有在联接表上有任何记录指向它们的生产者(注意选择正确的类型
):
在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
类生产者
定义self.with_some_product_规则
范围(条件:
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