我正在尝试学习多对多的关系,所以我有两个模型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
有人可以帮助我吗?
答案 0 :(得分:0)
在订单上使用has_and_belongs_to_many :products
,在产品上使用has_and_belongs_to_many :orders
。在这种情况下,您不会认为through
适合您要完成的任务。您也可以删除has_many :orders_products
行。