2016-09-26 49 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