has_many + dynamic conditions
Posted by michael.schaerfer on 06-Apr-09 at 16:36
In our latest project we had to implement condition-based categories. (like a category which holds all products with a price greater than X).
We serialized the condition-hash into a 'category_conditions' column and implemented a proxy-association method to evaluate the condition and return a scope (to keep method-chaining working):
1 class Category < ActiveRecord::Base 2 has_many :products do 3 def with_condition 4 scoped( { :conditions => proxy_owner.category_conditions } ) 5 end 6 end 7 end
No we can use it like this:
1 c = Category.create( :category_condition => ["price >= ?", 99] ) 2 c.products # => regular associated products 3 c.products.with_condition # => products with a price greater than 99
