【问题标题】:Finding through a joins table通过连接表查找
【发布时间】:2012-01-18 23:12:15
【问题描述】:

所以我有一个产品、product_tags 连接表和标签。我想使用 Product.find 查找具有特定标签名称的所有产品。这可能吗?

【问题讨论】:

    标签: ruby-on-rails-3 activerecord join


    【解决方案1】:

    您没有发布代码,但我认为这是您的设置:

    class Product < ActiveRecord::Base
       has_many :product_tags
       has_many :tags, :through => :product_tags
    end
    
    class Tag < ActiveRecord::Base
       has_many :product_tags
       has_many :products, :through => :product_tags
    end
    
    class ProductTag < ActiveRecord::Base
       belongs_to :product
       belongs_to :tag
    end
    

    然后您可以找到具有给定标签名称的所有产品,例如“cool_product”如下:

    cool_tag = Tag.find_by_name("cool_product")
    cool_tag.products # => list of all products
    

    为了参考和学习,我强烈建议阅读ActiveRecord::Associations::ClassMethods 上的整个文档页面。关联方法是 Active Record 中一些最被低估的特性。

    【讨论】:

    • 谢谢。但是,我需要使用 find 方法,因为我正在编写一个处理动态参数数组的搜索方法。我找到了一个解决方案,它只是在我的 find 参数末尾抛出“:include => :tags”。
    • 什么对象上的find方法?如果您需要更多详细信息,请发布一些代码。现在最好使用 Arel 的 .include 或 .joins 或自定义范围,而不是添加 :include => ... 选项。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    • 2019-01-26
    • 2017-01-23
    相关资源
    最近更新 更多