Rails 4多对多联合表

时间:2015-05-09 16:11:49

标签: has-many-through ruby-on-rails-4.2

我正在尝试学习多对多的关系,所以我有两个模型Order和Product,我用scaffold生成了一个连接表orders_products并跟随迁移:

create_table :orders_products do |t|

  t.references :order
  t.references :product
end

我有订购模式:

has_many :orders_products

has_many :products, through: :orders_products

accepts_nested_attributes_for :orders_products

在产品型号中:

has_many :orders_products

has_many :orders, through: :orders_products

accepts_nested_attributes_for :orders_products

在ordersproduct模型中:

belongs_to :order
belongs_to :product

按顺序控制器:

def new
@order = Order.new
@order.save

@entry = OrdersProduct.create
@entry.product_id = Product.find_by(name: 'default_product').id
@entry.order_id = @order.id    

end


def edit
@order = Order.find(params[:id])

@entries = @order.products

@order.save

end

private   
def order_params
  params.require(:order).permit(:name, orders_products: [:id, :order_id, :product_id])
end
end

当我在线上编辑时,我得到了未定义的方法`产品

@entries = @order.products

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

在订单上使用has_and_belongs_to_many :products,在产品上使用has_and_belongs_to_many :orders。在这种情况下,您不会认为through适合您要完成的任务。您也可以删除has_many :orders_products行。