0

私のアプリケーションには、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}%")

しかし、関連するプロパティ値に応じて、これらのアイテムをフィルター処理したいと考えています。プロパティ ID と各プロパティの値 (正確な値、最小値、または最大値) を受け取り、クエリを動的に構築するという考え方です。私のモデルを考えると、たとえば、これを行うにはどうすればよいですか: 名前に「foo」が含まれ、id=1 のプロパティの値が 2、id=2 のプロパティの値が 10 未満、id=8 のプロパティが必要なアイテムが必要です。 value>2 および value<5 を持ちます。

4

1 に答える 1

0

モデルから検索を実行PropertyValuationし、製品およびカテゴリ モデルに結合できます。

valuations = PropertyValuation.joins(:item)
                              .where(value: 2, property_id: 1)
                              .where('lower(items.name) LIKE ?', "%#{params[keywords].downcase}%")
items      = valuations.map(&:item)

このことをずっと簡単にする宝石があります.1つはRansack https://github.com/ernie/ransackです

Item.search(name_contains:                   params[:keywords], 
            product_valuations_value_equals: 2, 
            product_valuations_property_id:  1)
于 2013-04-09T04:32:16.813 に答える