Ruby-on-rails 在 Rails 中复制模型实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1262546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:37:23  来源:igfitidea点击:

Copy model instances in Rails

ruby-on-railsactiverecord

提问by user94154

I have a model Foowith attributes id, name, location. I have an instance of Foo:

我有一个Foo带有属性的模型id, name, location。我有一个实例Foo

f1 = Foo.new
f1.name = "Bar"
f1.location = "Foo York"
f1.save

I would like to copy f1and from that copy, create another instance of the Foomodel, but I don't want f1.idto carry over to f2.id(I don't want to explicitly assign that, I want the db to handle it, as it should).

我想复制f1并从该副本创建Foo模型的另一个实例,但我不想f1.id延续到f2.id(我不想明确分配,我希望数据库处理它,因为它应该) .

Is there a simple way to do this, other than manually copying each attribute? Any built in functions or would writing one be the best route?

除了手动复制每个属性之外,是否有一种简单的方法可以做到这一点?任何内置功能或编写一个是最好的路线?

Thanks

谢谢

回答by mydoghasworms

As per the following question, if you are using Rails >= 3.1, you can use object.dup:

根据以下问题,如果您使用的是 Rails >= 3.1,则可以使用object.dup

What is the easiest way to duplicate an activerecord record?

复制活动记录记录的最简单方法是什么?

回答by Vitaly Kushner

This is what ActiveRecord::Base#clonemethod is for:

这是ActiveRecord::Base#clone方法的用途:

@bar = @foo.clone

@bar.save

回答by bjelli

a wrongway to do this would be:

这样做的错误方法是:

f2 = Foo.new( f1.attributes )     # wrong!
f2.save                           # wrong!

or in one line, but still wrong:

或在一行中,但仍然错误

f2 = Foo.create( f1.attributes )  # wrong!

see comments for details

详情见评论

回答by Foram Thakral

You can make duplicate record in rails like

您可以在 rails 中进行重复记录,例如

@bar = @foo.dup
@bar.save!

回答by Shadwell

You could use the built-in attributesmethods that rails provides. E.g.

您可以使用attributesrails 提供的内置方法。例如

f2 = Foo.new(f1.attributes)

or

或者

f2 = Foo.new
f2.attributes = f1.attributes