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

所以基本上, a Producthas manyCategory和 a Categoryhas many Attributes

我想要的是Product模型内部的一个方法,它将返回:is_key设置为 true 的属性。

我尝试了一些变化

  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 回答