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

5

我有一个User模型和一个users表。一个用户可以拥有多个电话号码,因此我有一个单独的命名为Phone的模型。

我正在使用这个关联:

模型

User
     attr_accessible :id, :name, :screenname,:fullname,:phones_attributes
     has_many :phones,:dependent => :destroy

Phone
     attr_accessible :phone
     belongs to :users

以上代码运行良好。 管理员想将任何用户的记录复制到user_tempphone_temp表中(我有名为UserTempPhoneTemp的单独模型)。 我该怎么做?

你有另一个用户临时模型和电话临时模型吗? - Sabyasachi Ghosh
是的,正如我之前所提到的。 - Gagan
是的,下面这两种解决方案都适用于您 :) - Sabyasachi Ghosh
2个回答

11

最简单的方法是:

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
我知道这是老的,但你同时在进行创建和保存。你可能想要使用.new(...).save或者只是.create(...) - OzBarry

1
如果您有一个独立的temp_user模型,那么您可以像这样做
@user = User.find(params[:id]) # find original object
@temp_user = TempUser.create(@user.attributes)  

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接