将购买的产品存储到另一个型号order_products中

时间:2013-11-13 07:30:44

标签: ruby-on-rails ruby ruby-on-rails-3

**更新

我有以下型号:

product.rb

class Product

belongs_to :user
has_many :line_items
has_many :orders, :through => :order_products
has_many :order_products

lineitem.rb

class LineItem

belongs_to :product
belongs_to :cart
belongs_to: order

order.rb

class Order

belongs_to :user
belongs_to :product
has_many :purchases
has_many :line_items, :dependent => :destroy
has_many :orders, :through => :order_products
has_many :order_products

accepts_nested_attributes_for :order_products

order_product.rb

class OrderProduct < ActiveRecord::Base
    belongs_to :order
    belongs_to :product
end

order_controller.rb

if @order.save

  if @order.purchase
    Cart.destroy(session[:cart_id])
    session[:cart_id] = nil 

以上是我对模特的联想。在购买购物车后,我在从line_items存储多个product_id时遇到了一个大问题。

我相信在if@order.purchase之后应该有代码才能运作。我怎么想将order_id和product_id存储到order_products表中。

有人可以帮我吗?

在这里感谢任何帮助。感谢

1 个答案:

答案 0 :(得分:0)

您似乎可以从了解accepts_nested_attributes_for以及foreign_keys如何使用ActiveRecord

中受益

外键

如果您正确设置了ActiveRecord关联,则可以通过一次通话调用类似@product.line_items的内容

ActiveRecord(以及一般的关系数据库)关闭foreign_keys,这基本上是对另一个表中模型id的引用。当您说要在另一个表中输入order_id时,您真正需要了解的是如何让ActiveRecord将正确的外键放入记录中

我写这篇文章的原因是因为如果你能理解ActiveRecord是如何工作的,那么你将处于更有利的位置来解决你的问题


<强> Accepts_Nested_Attributes_For

我相信能帮助你的功能是accepts_nested_attributes_for - 它基本上允许你通过当前模型保存另一个模型的数据

它的工作原理如下:

#/app/models/order.rb
class Order

belongs_to :user
belongs_to :product
has_many :purchases
has_many :line_items, :dependent => :destroy
has_many :orders, :through => :order_products
has_many :order_products

accepts_nested_attributes_for :order_products

这意味着如果您将适当的嵌套属性发送到此模型,它将为您处理:order_products

为此,您需要将此添加到您的表单和&amp;控制器:

#app/controllers/orders_controller.rb
def new
    @order = Order.new
    @order.order_products.build
end

private
def strong_params
    params.require(:order).permit(:standard_params,  order_products_attributes: [:name]  )
end


#app/views/orders/new.html.erb
<%= form_for @order do |f| %>
    <%= f.fields_for :order_products do |product| %>
         <%= product.text_field :name %>
    <% end %>
<% end %>