2016-09-26 56 views
2

我對關聯感到困惑。 我試圖寫下面的代碼,但軌道返回我「未定義的方法`subs'」。如何應用關聯規則

def show 
    @product = Product.find(params[:id]) 
    @materials = @product.materials.subs 
    respond_to do |format| 
    format.json { render json: [ @product,@materials ]} 
    end 
end 

我想要產品模型涉及子模型,我得到子模型的記錄。 如果有人知道這個問題解決請告訴我。

class Product < ActiveRecord::Base 
    has_many :product_materials 
    has_many :materials, :through => :product_materials 
end 

class ProductMaterial < ActiveRecord::Base 
    belongs_to :product 
    belongs_to :material 
end 

class Material < ActiveRecord::Base 
    has_many :product_materials 
    has_many :products, :through => :product_materials 
    has_many :material_subs 
    has_many :subs, :through => :material_subs 
end 

class MaterialSub < ActiveRecord::Base 
    belongs_to :material 
    belongs_to :sub 
end 

class Sub < ActiveRecord::Base 
    has_many :material_subs 
    has_many :materials, :through => :material_subs 
end 

回答

2

@product.materials是一個數組,你不能鏈的陣列上的關聯

@product = Product.includes(materials: :subs).find(params[:id]) 
@materials = @product.materials.flat_map(&:subs) 

這將循環材料上和將返回subs每個material

+1

'要求1分鐘ago', '1分鐘前回答' - 這真是太快了!提供給n + 1的 –

+1

,使用'includes' –

+0

完全解決。非常感謝!! – johnny