Rails ActionRecord 中使用 duplicate 后相关联的记录怎么复制?

ziu · March 23, 2014 · 1699 hits

数据库关系:

class Cart < ActiveRecord::Base
  has_many :line_items, dependent: :destroy
  belongs_to :user

现在要实现登录后将购物车转到登录用户的 id 下:

##user.rb:
 def cartdup(record)
    if self.cart.nil?
      self.cart=record.dup
    end
    self.cart 
  end

##sessions_helper:

def sign_in(user)
    remember_token=User.new_remember_token
    cookies.permanent[:remember_token]=remember_token
    user.update_attribute(:remember_token,User.encrypt(remember_token))
    self.current_user=user
 if @temp_cart=Cart.find(session[:cart_id])
      self.current_user.cartdup(@temp_cart)
      Cart.destroy(session[:cart_id])
      session[:cart_id]=nil
 end
end 

但是这只是新建了一个购物车,原先购物车的物品 (lineitems) 丢失了。 请问如何解决这个问题? 谢谢。

No Reply at the moment.
You need to Sign in before reply, if you don't have an account, please Sign up first.