我有以下型号:
product.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
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
purchase.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被销毁后,我无法检索相关产品。
在此感谢任何帮助。
答案 0 :(得分: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
答案 1 :(得分: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
推到别处,以便在销毁购物车之前记录它们。