1

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']

私はこれを出発点として使用していました。

4

1 に答える 1

1

has_many :throughjoin 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
于 2013-01-19T16:56:50.227 に答える