0

我有以下型号:

产品.rb

class Product

has_many :purchases
has_many :line_items
has_many :orders, :through => :order_products

lineitem.rb

class LineItem

belongs_to :product
belongs_to :cart
belongs_to: 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

购买.rb

class Purchase

belongs_to :order
belongs_to :product

更新:

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 被销毁。

有谁知道我如何将所有购买的物品存储到购买中或任何其他更好的方法让我展示用户购买的产品?

我最初尝试检索 line_items 并且它有效。但是,在 line_items 被销毁后,我无法检索相关产品。

感谢这里的任何帮助。

4

2 回答 2

0

您需要查看http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association关联。

 User
   has_many :orders
   has_many :products, through: :orders

 Order
   has_many :line_items
   has_many :products, through: :line_items
于 2013-11-11T12:38:12.240 回答
0

您可以尝试order_history为每个用户制作一个 -

user.rb

def order_history
  #set this up according to how your models are related, etc  
  #with the idea being to call @user.order_history and getting an array of previous orders  
end

然后在order_controller.rb

if @order.save

      if @order.purchase
        #adapt this pseudocode to suit your needs and 
        #according to how you've defined `@user.order_history
        current_user.order_history = current_user.order_history + @order.line_items
        Cart.destroy(session[:cart_id])
        session[:cart_id] = nil 

本质上,将其他地方推到line_items其他地方,以便在销毁购物车之前对它们进行记录。

于 2013-11-11T13:03:02.617 回答