【问题标题】:Rails has_many through relationRails has_man 通过关系
【发布时间】:2023-03-07 05:46:01
【问题描述】:

我正在尝试使用 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 作为起点。

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

    • 我发帖后意识到我需要做些别的事情来实现我想要的,而您的回答似乎正是我所需要的!我将尝试您提供的内容并明天接受!非常感谢
    • 非常感谢 Matthew,我通过以下方式实现了它:gist.github.com/4577958
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多