0

私は次のモデルを持っています:

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

購入.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

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 に答える
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 に答える