简体   繁体   中英

Rails has_many through relation

I am trying to use the has_many :through relation in rails to return a set of product features. Please see this gist for the models: https://gist.github.com/4572661

I know how to do this using the ProductFeature model directly, but I really do not want to have to interact with it directly.

I want to be able to do this:

features = Product.features

So it returns:

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

But I can only get it to return:

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

I was using this as a starting point.

has_many :through is designed to regard the join table as nothing more than that.

Any columns on the join will be ignored from the association.

As such we have to use product_features

product.product_features(include: :feature)

Thereby we can say

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

  name = feature.name
  value = pf.value
end

If you use this type of thing a lot, I'd be inclined to do something like this;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM