2015-05-09 112 views
0

我努力學習多對多的關係,所以我有兩個模型訂單和產品,我用腳手架生成的連接表orders_products與後續遷移:軌道4多對多的聯合表

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

在訂購時使用has_and_belongs_to_many :products,在產品上使用has_and_belongs_to_many :orders。在這種情況下,您不認爲through適合您要完成的任務。您也可以刪除has_many :orders_products行。

+0

正常工作......謝謝! – druido82