在我的 ROR 应用程序中,我有模型 Category、Item、Property 和 PropertyValuation。这个想法是一个类别包含项目,一个项目有几个属性。PropertyValuation 的目的是存储特定项目的属性值。模型定义如上:
class Category < ActiveRecord::Base
attr_accessible :name, :description, :parent, :children, :items, :parent_id
has_many :children, :class_name => "Category", :foreign_key => "parent_id", :dependent => :nullify
belongs_to :parent, :class_name => "Category"
has_many :categorizations
has_many :items, :through => :categorizations
end
class Item < ActiveRecord::Base
attr_accessible :name, :description, :property_valuations, :barcode
has_many :property_valuations, :dependent => :destroy
has_many :properties, :through => :property_valuations
has_many :categorizations
has_many :categories, :through => :categorizations
end
class Property < ActiveRecord::Base
attr_accessible :name, :description, :value_type, :unit, :unit_id
has_many :property_valuations, :dependent => :destroy
has_many :items, :through => :property_valuations
has_many :property_ranges, :dependent => :destroy
belongs_to :unit
end
class PropertyValuation < ActiveRecord::Base
attr_accessible :property, :item, :value, :categorization
belongs_to :property
belongs_to :item
end
现在我的问题是,我已经成功地通过这样做来按名称过滤类别项目:
@category.items.where("lower(items.name) like ?", "%#{params[:keywords].downcase}%")
但现在我还想根据关联的属性值过滤这些项目。示例:我想要名称包含“foo”的类别项目,其中属性“A”的值为 1,属性 B 的值为 2,依此类推。如何实现这样的查询?