0
我有一個有很多目錄的商店,並且每個目錄又有許多產品。有效記錄:查詢嵌套多對多模型
該產品和目錄共享多對多的關係。 一個產品可以屬於許多目錄和副詩。
所以,我的模型定義是這樣的:
class Store < ActiveRecord::Base
has_many :store_catalogs
has_many :catalogs, :through => :store_catalogs
end
class StoreCatalog < ActiveRecord::Base
belongs_to :store
belongs_to :catalog
end
class Catalog < ActiveRecord::Base
has_many :store_catalogs
has_many :stores, :through => :store_catalogs
has_and_belongs_to_many :product_set, :class_name => "Product"
end
class Product < ActiveRecord::Base
has_and_belongs_to_many :catalogs
end
現在,我想訪問所有屬於存儲產品。 我如何將這些鏈接在一起,以便我得到它?請建議。
我試着從軌道控制檯拉出數據的各種組合,不知道如果控制檯本身限制基於關係的查詢任何機會(雖然我想相信它不)。
Store.find(ID).product_set犯規,雖然拉動產品。未定義的方法'product_set'爲# .....'method_missing' –
thanikkal
是的,那是因爲在您的代碼中,Store模型沒有直接鏈接到它的任何產品。使用現在使用的模型設置,您需要進行深度嵌套才能到達產品。哪些工作,但我真的沒有看到你在這種情況下使用它的任何理由,我給你的代碼應該做的伎倆。如果你看看我的答案,你會看到Store has_many:這些產品可以讓你做'Store.find(id).products' – nbon