【问题标题】:How do you access inner relations in rails active association?您如何访问 rails active 关联中的内部关系?
【发布时间】:2012-12-13 00:26:38
【问题描述】:

我以这种方式设置了我的同事。

事件 - (has_many) - 供应商 - (has_many) - 产品 - (has_many) - productTags - (belongs_to) - 标签

我正在尝试检索一个事件的标签数组,但只包括那些有产品的标签。

最初我可以通过

访问事件模型
@event = Event.find(1)

我很难从关联的兔子洞中找到所有产品的标签数组。

我们将不胜感激任何帮助或推动正确方向的努力。

非常感谢

【问题讨论】:

    标签: ruby-on-rails activerecord model associations


    【解决方案1】:
    class Event < ActiveRecord::Base
    
      def tags
        Tag.includes(:product_tags => {:product => {:vendor => {:event => {}}}}).where(["events.id = ?", self.id])
      end
    
    end
    
    @event = Event.find(1)
    @event.tags
    

    【讨论】:

    • .includes 可以替换为 .joins
    • +1 好答案。您可以将传递给includes(或joins)的哈希简化为::product_tags =&gt; {:product =&gt; {:vendor =&gt; :event }}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多