Rails 4 多对多联合 table
Rails 4 many to many joint table
我正在尝试学习多对多关系,所以我有两个模型 Order 和 Product,我使用脚手架生成了一个连接 table 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
在订单产品型号:
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
当我在线上编辑时,我得到了未定义的方法`products
@entries = @order.products
有人可以帮助我吗?
在订单上使用 has_and_belongs_to_many :products
,在产品上使用 has_and_belongs_to_many :orders
。在这种情况下,我认为 through
不适合您要实现的目标。您也可以删除 has_many :orders_products
行。
我正在尝试学习多对多关系,所以我有两个模型 Order 和 Product,我使用脚手架生成了一个连接 table 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
在订单产品型号:
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
当我在线上编辑时,我得到了未定义的方法`products
@entries = @order.products
有人可以帮助我吗?
在订单上使用 has_and_belongs_to_many :products
,在产品上使用 has_and_belongs_to_many :orders
。在这种情况下,我认为 through
不适合您要实现的目标。您也可以删除 has_many :orders_products
行。