Rails 4多对多联合表

时间:2021-07-02 09:57:28

I'm trying to learn many to many relationship, so I have two model Order and Product, I generated with scaffold a join table orders_products with the follow migration:

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

create_table :orders_products do |t|

  t.references :order
  t.references :product
end

I have in order model:

我有订单型号:

has_many :orders_products

has_many :products, through: :orders_products

accepts_nested_attributes_for :orders_products

in product model:

在产品型号中:

has_many :orders_products

has_many :orders, through: :orders_products

accepts_nested_attributes_for :orders_products

in ordersproduct model:

在ordersproduct模型:

belongs_to :order
belongs_to :product

in order controller:

在控制器中:

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

I am getting undefined method `products when I am in edit on the line

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

@entries = @order.products

Someone can help me?

有人可以帮帮我吗?

1 个解决方案

#1


Use has_and_belongs_to_many :products on Order and has_and_belongs_to_many :orders on Product. Wouldn't think through is appropriate in this scenario for what you are trying to accomplish. You can also remove the has_many :orders_products lines as well.

在订单上使用has_and_belongs_to_many:产品,在产品上使用has_and_belongs_to_many:订单。在这种情况下,你想要完成的事情是不合适的。您也可以删除has_many:orders_products行。

#1


Use has_and_belongs_to_many :products on Order and has_and_belongs_to_many :orders on Product. Wouldn't think through is appropriate in this scenario for what you are trying to accomplish. You can also remove the has_many :orders_products lines as well.

在订单上使用has_and_belongs_to_many:产品,在产品上使用has_and_belongs_to_many:订单。在这种情况下,你想要完成的事情是不合适的。您也可以删除has_many:orders_products行。