【发布时间】:2013-01-20 23:11:55
【问题描述】:
我的Product 模型中有这种关系:
has_many :features, :class_name => 'ProductFeature', :source => :product_feature, :include => :feature
所以我可以Product.features
效果很好。但我希望能够在必要时按feature 表中的字段过滤它。以伪代码为例:
find all product features where feature is comparable
compare 是 feature 上的布尔字段。
我已经尝试了 2 个小时,但无法弄清楚(没有完全编写新查询)。我不知道如何从Product.features 关系中访问feature 表的字段,因为它似乎只能过滤product_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
feature.rb
class Feature < ActiveRecord::Base
attr_accessible :name, :compare
end
我希望能够查询属于product 和feature 的product_features,其中Feature.compare 是true。像这样的:
产品.rb
def features_compare
product_features.where(:compare => true)
end
这会引发错误,因为 compare 在 Feature 模型中,而不是 ProductFeature。我在 product_feature.rb 中尝试了以下内容:
delegate :compare, :to => :feature
但我没有帮助。
我将在几个小时内为此添加赏金,所以请帮助我!
【问题讨论】:
-
我对应用程序的组织感到困惑。所以你有一个 features 表和一个 product_features 表,一个 Feature 模型和一个 ProductFeature 模型?
-
另外,你不需要 :source 属性,因为
has_many :features不是has_many :through关联。 -
我开始怀疑你是否也需要
:include => :feature部分,除非 ProductFeature 有一个功能。 -
我知道你会怎么样!我有一个特征模型,其中包含一组特征,例如“颜色”、“尺寸”、“形状”等。然后是一个 ProductFeature 模型,其中包含指向产品和特征的链接,并包含一个“值”,例如“ black', 'medium', 'round' 等。我在 Product 模型上将关系重命名为 'features' 而不是 'product_features' 以提高可读性(或者我希望如此大声笑)
-
我需要包含,所以我可以通过关系访问功能名称
标签: ruby-on-rails ruby ruby-on-rails-3 arel