0

私は次のモデルを持っています(不要な部分を取り除いています):

class Product < ActiveRecord::Base
  has_many :categories, :dependent => :destroy
end

class Category < ActiveRecord::Base
  belongs_to :product
  has_many :attributes, :dependent => :destroy
end

class Attribute < ActiveRecord::Base
  belongs_to :category

  attr_accessible :name, :value, :is_key
end

つまり、基本的に、 aProductは多数Categoryあり、 aCategoryは多数ありAttributesます。

私が欲しいのは、trueProductに設定された属性を返すモデル内のメソッドです。:is_key

私はいくつかのバリエーションを試しました

  def key_attributes
    Attribute.joins(:category).where(:attributes => {:is_key => true}, :category => {:product_id => self.id}).all
  end

しかし、成功しませんでした。

その中に何を入れるべきkey_attributesですか?

4

1 に答える 1

1

最初に行うべきサウンド:

has_many :attributes, :through => :categories

次に、単に次のようにする必要があります。

joins(:attributes).where(:attributes => { :is_key => true })

関連付け拡張を次のように定義することもできます。

has_many :attributes, :through => :categories do
  def is_key(value=true)
    where(:is_key => value)
  end
end
于 2013-07-05T00:06:47.043 に答える