0
所以我有一個產品,product_tags連接表和標籤。我想使用Product.find查找具有特定標籤名稱的所有產品。這可能嗎?通過連接表查找
所以我有一個產品,product_tags連接表和標籤。我想使用Product.find查找具有特定標籤名稱的所有產品。這可能嗎?通過連接表查找
你沒有張貼代碼,但我想這是你的設置:
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方法,因爲我正在編寫一個處理動態數組參數的搜索方法。我發現了一個解決方案,它在我的查找參數結束時拋出「:include =>:tags」。 –
關於什麼對象的find方法?請張貼一些代碼,如果你想要更多的細節。現在最好使用Arel的.include或.joins或自定義範圍,而不是添加:include => ...選項。 –