1

私のProductモデルには次の関係があります。

has_many :features, :class_name => 'ProductFeature', :source => :product_feature, :include => :feature

だから私はできるProduct.features

これは正常に動作します。featureしかし、必要に応じて、テーブル内のフィールドでそれをフィルタリングできるようにしたいと考えています。たとえば、擬似コードでは次のようになります。

find all product features where feature is comparable

compareの bool フィールドfeatureです。

私は2時間しっかりと試してきましたが、それを理解できません(新しいクエリを完全に作成しないと)。フィールドでのみフィルタリングできるように見えるためfeature、リレーションからテーブルのフィールドにアクセスする方法がわかりません。Product.featuresproduct_features

これは私がこれまでに思いついたものです:

def features_compare
  features.feature.where(:compare => true)
end

featureしかし、私が理解している有効な方法ではないと言っているだけです。

編集

関係がより明確になるように、モデルを更新しました。

product.rb:

class Product < ActiveRecord::Base
  belongs_to :company
  belongs_to :insurance_type

  has_many :product_features
  has_many :reviews

  attr_accessible :description, :name, :company
end

product_feature.rb:

class ProductFeature < ActiveRecord::Base
  belongs_to :product
  belongs_to :feature

  delegate :name, :to => :feature

  attr_accessible :value
end

機能.rb

class Feature < ActiveRecord::Base
  attr_accessible :name, :compare
end

product_featuresに属し、productfeatureどこにFeature.compareあるかを照会できるようにしたいと考えていますtrue。このようなもの:

product.rb

def features_compare
  product_features.where(:compare => true)
end

ではなくモデルcompare内にあるため、これはエラーをスローします。product_feature.rb で次のことを試しました。FeatureProductFeature

delegate :compare, :to => :feature

しかし、私は助けませんでした。

数時間以内にこれに賞金を追加しますので、助けてください!

4

3 に答える 3

2

find all product features where feature is comparableただです

ProductFeature.joins(:feature).where(:feature => {:compare => true})

スコープを導入することで、もう少し再利用可能にすることができます。

#in product_feature.rb
scope :with_feature_like, lambda do |filter|
   joins(:feature).where(:feature => filter)
end

#elsewhere
ProductFeature.with_feature_like(:compare => true)

#all the product features of a certain product with at comparable features
some_product.product_features.with_feature_like(:compare => true)

最後に、同等の機能を持つ製品機能を持つすべての製品が必要な場合は、次のようなものが必要です。

Product.joins(:product_features => :feature).where(:feature => {:compare => true})

もちろん、スコープに変えることもできますProduct

于 2013-01-23T10:51:33.800 に答える
1

これは has_many :through 関係のようです。これを変更してみてください:

has_many :features, :class_name => 'ProductFeature', :source => :product_feature, :include => :feature

これに:

has_many :product_features
has_many :features, :through => :product_features

ProductFeature モデルにこれがある限り:

belongs_to :product
belongs_to :feature

また、product_features (product_id、feature_id) に適切な列があれば、その製品の機能と、Product と ProductFeature の両方のすべての属性にアクセスできるはずです。

ここを参照してください:

http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

編集: 機能フィールドでフィルタリングする方法は次のとおりです。

Product.joins(:features).where(:features => {:name => "Size"})
于 2013-01-20T23:18:35.610 に答える
0

@product.each |p| { p.features.where(:comparable => true) }おそらくここであなたの最善の策ですが、私は悟りを開くことにオープンです。

于 2013-01-20T23:20:50.893 に答える