代码之家  ›  专栏  ›  技术社区  ›  Gagan

在rails中将一个表记录复制到另一个表中

  •  5
  • Gagan  · 技术社区  · 12 年前

    我有一个 使用者 模型和 用户 桌子一个用户可以有很多电话号码,所以我有一个名为 Phone . 我使用此关联是为了:

    模型

    User
         attr_accessible :id, :name, :screenname,:fullname,:phones_attributes
         has_many :phones,:dependent => :destroy
    
    Phone
         attr_accessible :phone
         belongs to :users
    

    以上代码工作正常。 管理员希望将任何用户的记录复制到 user_temp phone_temp 表(我有单独的模型 用户温度 电话温度 ).

    我该怎么做?

    2 回复  |  直到 12 年前
        1
  •  11
  •   lurker    9 年前

    最简单的方法是:

    phone_item = Phone.find(x)   # Get the phone item you want to copy
                                 # you may have obtained this some other way
    
    PhoneTemp.create(phone_item.attributes) if phone_item
    

    用户也是如此。

        2
  •  1
  •   Sabyasachi Ghosh    12 年前

    如果你有一个单独的temp_user模型,那么你可以这样做

    @user = User.find(params[:id]) # find original object
    @temp_user = TempUser.create(@user.attributes)  
    
    推荐文章