如何应用关联规则

时间:2016-09-26 12:52:50

标签: ruby-on-rails ruby

我对协会感到困惑。 我试着写下面的代码,但是rails返回了“undefined method`sub'”。

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

我希望产品型号与Sub模型相关,我得到Sub模型记录。 如果有人知道要解决这个问题,请告诉我。

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

1 个答案:

答案 0 :(得分:2)

@product.materials是一个数组,您不能在数组上链接关联

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

这会遍历材料,并会为每个subs

返回material