Rails has_many通过关系

时间:2013-01-19 13:31:45

标签: ruby-on-rails ruby ruby-on-rails-3 has-many-through

我正在尝试使用rails中的has_many :through关系来返回一组产品功能。有关模型,请参阅此要点:https://gist.github.com/4572661

我知道如何直接使用ProductFeature模型,但我真的不想直接与它进行交互。

我希望能够做到这一点:

features = Product.features

所以它返回:

[id: 1, name: 'Colour', value: 'Blue'], [id: 2, name: 'Size', value: 'M'], [id: 3, name: 'Shape', value: 'Round']

但我只能让它回来:

[id: 1, name: 'Colour'], [id: 2, name: 'Size'], [id: 3, name: 'Shape']

我使用this作为起点。

1 个答案:

答案 0 :(得分:1)

has_many :through旨在将join table视为仅此而已。

联接中的任何列都将被忽略。

因此我们必须使用product_features

product.product_features(include: :feature)

因此我们可以说

product.product_features(include: :feature).each do |pf|
  feature = pf.feature

  name = feature.name
  value = pf.value
end

如果你经常使用这类东西,我会倾向于做这样的事情;

class Product
  # always eager load the feature
  has_many :product_features, include: :feature
end

class ProductFeature
  # delegate the feature_name
  delegate :name, to: :feature
end