<p>I want to make a copy of an ActiveRecord object, changing a single field in the process (in addition to the <strong>id</strong>).  What is the simplest way to accomplish this?</p>
<p>I realize I could create a new record, and then iterate over each of the fields copying the data field-by-field - but I figured there must be an easier way to do this.</p>
<p>Perhaps something like this:</p>
<pre class="lang-ruby prettyprint-override"><code> new_record = Record.copy(:id)
</code></pre>

[{'answer_id': 60053, 'author': 'Michael Sepcot', 'author_id': 6033, 'author_profile': 'https://Stackoverflow.com/users/6033', 'pm_score': 10, 'selected': True, 'text': '<p>To get a copy, use the <a href="https://api.rubyonrails.org/classes/ActiveRecord/Core.html#method-i-dup" rel="noreferrer">dup</a> (or clone for &lt; rails 3.1+) method:</p>\n<pre><code>#rails &gt;= 3.1\nnew_record = old_record.dup\n\n# rails &lt; 3.1\nnew_record = old_record.clone\n</code></pre>\n<p>Then you can change whichever fields you want.</p>\n<p><a href="http://api.rubyonrails.com/classes/ActiveRecord/Base.html#M001363" rel="noreferrer">ActiveRecord overrides the built-in Object#clone</a> to give you a new (not saved to the DB) record with an unassigned ID.<br />\nNote that it does not copy associations, so you\'ll have to do this manually if you need to.</p>\n<p><a href="https://gist.github.com/994614" rel="noreferrer">Rails 3.1 clone is a shallow copy, use dup instead...</a></p>\n'}, {'answer_id': 62925, 'author': 'François Beausoleil', 'author_id': 7355, 'author_profile': 'https://Stackoverflow.com/users/7355', 'pm_score': 5, 'selected': False, 'text': '<p>I usually just copy the attributes, changing whatever I need changing:</p>\n\n<pre><code>new_user = User.new(old_user.attributes.merge(:login =&gt; "newlogin"))\n</code></pre>\n'}, {'answer_id': 63032, 'author': 'Phillip Koebbe', 'author_id': 7283, 'author_profile': 'https://Stackoverflow.com/users/7283', 'pm_score': 6, 'selected': False, 'text': "<p>Depending on your needs and programming style, you can also use a combination of the new method of the class and merge. For lack of a better <em>simple</em> example, suppose you have a task scheduled for a certain date and you want to duplicate it to another date. The actual attributes of the task aren't important, so:</p>\n\n<pre>\nold_task = Task.find(task_id)\nnew_task = Task.new(old_task.attributes.merge({:scheduled_on => some_new_date}))\n</pre>\n\n<p>will create a new task with <code>:id => nil</code>, <code>:scheduled_on => some_new_date</code>, and all other attributes the same as the original task. Using Task.new, you will have to explicitly call save, so if you want it saved automatically, change Task.new to Task.create.</p>\n\n<p>Peace. </p>\n"}, {'answer_id': 6957504, 'author': 'bradgonesurfing', 'author_id': 158285, 'author_profile': 'https://Stackoverflow.com/users/158285', 'pm_score': 5, 'selected': False, 'text': '<p>Use <a href="http://api.rubyonrails.org/classes/ActiveRecord/Core.html#method-i-dup" rel="noreferrer">ActiveRecord::Base#dup</a> if you don\'t want to copy the id</p>\n'}, {'answer_id': 7265525, 'author': 'raidfive', 'author_id': 110315, 'author_profile': 'https://Stackoverflow.com/users/110315', 'pm_score': 3, 'selected': False, 'text': '<p>If you need a deep copy with associations, I recommend the <a href="https://github.com/moiristo/deep_cloneable">deep_cloneable</a> gem.</p>\n'}, {'answer_id': 9485535, 'author': 'Vaughn Draughon', 'author_id': 1238269, 'author_profile': 'https://Stackoverflow.com/users/1238269', 'pm_score': 5, 'selected': False, 'text': '<p>You may also like the <a href="https://rubygems.org/gems/amoeba" rel="noreferrer">Amoeba gem</a> for ActiveRecord 3.2.</p>\n\n<p>In your case, you probably want to make use of the <code>nullify</code>, <code>regex</code> or <code>prefix</code> options available in the configuration DSL.</p>\n\n<p>It supports easy and automatic recursive duplication of <code>has_one</code>, <code>has_many</code> and <code>has_and_belongs_to_many</code> associations, field preprocessing and a highly flexible and powerful configuration DSL that can be applied both to the model and on the fly.</p>\n\n<p>be sure to check out the <a href="https://github.com/rocksolidwebdesign/amoeba#readme" rel="noreferrer">Amoeba Documentation</a> but usage is pretty easy...</p>\n\n<p>just</p>\n\n<pre><code>gem install amoeba\n</code></pre>\n\n<p>or add </p>\n\n<pre><code>gem \'amoeba\'\n</code></pre>\n\n<p>to your Gemfile</p>\n\n<p>then add the amoeba block to your model and run the <code>dup</code> method as usual</p>\n\n<pre><code>class Post &lt; ActiveRecord::Base\n  has_many :comments\n  has_and_belongs_to_many :tags\n\n  amoeba do\n    enable\n  end\nend\n\nclass Comment &lt; ActiveRecord::Base\n  belongs_to :post\nend\n\nclass Tag &lt; ActiveRecord::Base\n  has_and_belongs_to_many :posts\nend\n\nclass PostsController &lt; ActionController\n  def some_method\n    my_post = Post.find(params[:id])\n    new_post = my_post.dup\n    new_post.save\n  end\nend\n</code></pre>\n\n<p>You can also control which fields get copied in numerous ways, but for example, if you wanted to prevent comments from being duplicated but you wanted to maintain the same tags, you could do something like this:</p>\n\n<pre><code>class Post &lt; ActiveRecord::Base\n  has_many :comments\n  has_and_belongs_to_many :tags\n\n  amoeba do\n    exclude_field :comments\n  end\nend\n</code></pre>\n\n<p>You can also preprocess fields to help indicate uniqueness with both prefixes and suffixes as well as regexes. In addition, there are also numerous options so you can write in the most readable style for your purpose:</p>\n\n<pre><code>class Post &lt; ActiveRecord::Base\n  has_many :comments\n  has_and_belongs_to_many :tags\n\n  amoeba do\n    include_field :tags\n    prepend :title =&gt; "Copy of "\n    append :contents =&gt; " (copied version)"\n    regex :contents =&gt; {:replace =&gt; /dog/, :with =&gt; "cat"}\n  end\nend\n</code></pre>\n\n<p>Recursive copying of associations is easy, just enable amoeba on child models as well</p>\n\n<pre><code>class Post &lt; ActiveRecord::Base\n  has_many :comments\n\n  amoeba do\n    enable\n  end\nend\n\nclass Comment &lt; ActiveRecord::Base\n  belongs_to :post\n  has_many :ratings\n\n  amoeba do\n    enable\n  end\nend\n\nclass Rating &lt; ActiveRecord::Base\n  belongs_to :comment\nend\n</code></pre>\n\n<p>The configuration DSL has yet more options, so be sure to check out the documentation.</p>\n\n<p>Enjoy! :)</p>\n'}, {'answer_id': 33379580, 'author': 'esbanarango', 'author_id': 1136821, 'author_profile': 'https://Stackoverflow.com/users/1136821', 'pm_score': 0, 'selected': False, 'text': '<p>You can also check the <a href="https://github.com/esbanarango/acts_as_inheritable" rel="nofollow">acts_as_inheritable</a> gem.</p>\n\n<p>"Acts As Inheritable is a Ruby Gem specifically written for Rails/ActiveRecord models. It is meant to be used with the <a href="https://github.com/esbanarango/acts_as_inheritable#self-referential-association" rel="nofollow">Self-Referential Association</a>, or with a model having a parent that share the inheritable attributes. This will let you inherit any attribute or relation from the parent model."</p>\n\n<p>By adding <code>acts_as_inheritable</code> to your models you will have access to these methods:</p>\n\n<p><strong>inherit_attributes</strong></p>\n\n<pre class="lang-ruby prettyprint-override"><code>class Person &lt; ActiveRecord::Base\n\n  acts_as_inheritable attributes: %w(favorite_color last_name soccer_team)\n\n  # Associations\n  belongs_to  :parent, class_name: \'Person\'\n  has_many    :children, class_name: \'Person\', foreign_key: :parent_id\nend\n\nparent = Person.create(last_name: \'Arango\', soccer_team: \'Verdolaga\', favorite_color:\'Green\')\n\nson = Person.create(parent: parent)\nson.inherit_attributes\nson.last_name # =&gt; Arango\nson.soccer_team # =&gt; Verdolaga\nson.favorite_color # =&gt; Green\n</code></pre>\n\n<p><strong>inherit_relations</strong></p>\n\n<pre class="lang-ruby prettyprint-override"><code>class Person &lt; ActiveRecord::Base\n\n  acts_as_inheritable associations: %w(pet)\n\n  # Associations\n  has_one     :pet\nend\n\nparent = Person.create(last_name: \'Arango\')\nparent_pet = Pet.create(person: parent, name: \'Mango\', breed:\'Golden Retriver\')\nparent_pet.inspect #=&gt; #&lt;Pet id: 1, person_id: 1, name: "Mango", breed: "Golden Retriver"&gt;\n\nson = Person.create(parent: parent)\nson.inherit_relations\nson.pet.inspect # =&gt; #&lt;Pet id: 2, person_id: 2, name: "Mango", breed: "Golden Retriver"&gt;\n</code></pre>\n\n<p>Hope this can help you.</p>\n'}, {'answer_id': 40329894, 'author': 'ThienSuBS', 'author_id': 4631412, 'author_profile': 'https://Stackoverflow.com/users/4631412', 'pm_score': 2, 'selected': False, 'text': '<p>The easily way is:</p>\n\n<pre><code>#your rails &gt;= 3.1 (i was done it with Rails 5.0.0.1)\n  o = Model.find(id)\n # (Range).each do |item|\n (1..109).each do |item|\n   new_record = o.dup\n   new_record.save\n end\n</code></pre>\n\n<p>Or </p>\n\n<pre><code># if your rails &lt; 3.1\n o = Model.find(id)\n (1..109).each do |item|\n   new_record = o.clone\n   new_record.save\n end     \n</code></pre>\n'}, {'answer_id': 49322942, 'author': 'Paulo Fidalgo', 'author_id': 1006863, 'author_profile': 'https://Stackoverflow.com/users/1006863', 'pm_score': 0, 'selected': False, 'text': '<p>Since there could be more logic, when duplicating a model, I would suggest to create a new class, where you handle all the needed logic.\nTo ease that, there\'s a gem that can help: <a href="https://github.com/palkan/clowne" rel="nofollow noreferrer">clowne</a></p>\n\n<p>As per their documentation examples, for a User model:</p>\n\n<pre><code>class User &lt; ActiveRecord::Base\n  # create_table :users do |t|\n  #  t.string :login\n  #  t.string :email\n  #  t.timestamps null: false\n  # end\n\n  has_one :profile\n  has_many :posts\nend\n</code></pre>\n\n<p>You create your cloner class:</p>\n\n<pre><code>class UserCloner &lt; Clowne::Cloner\n  adapter :active_record\n\n  include_association :profile, clone_with: SpecialProfileCloner\n  include_association :posts\n\n  nullify :login\n\n  # params here is an arbitrary Hash passed into cloner\n  finalize do |_source, record, params|\n    record.email = params[:email]\n  end\nend\n\nclass SpecialProfileCloner &lt; Clowne::Cloner\n  adapter :active_record\n\n  nullify :name\nend\n</code></pre>\n\n<p>and then use it:</p>\n\n<pre><code>user = User.last\n#=&gt; &lt;#User(login: \'clown\', email: \'clown@circus.example.com\')&gt;\n\ncloned = UserCloner.call(user, email: \'fake@example.com\')\ncloned.persisted?\n# =&gt; false\n\ncloned.save!\ncloned.login\n# =&gt; nil\ncloned.email\n# =&gt; "fake@example.com"\n\n# associations:\ncloned.posts.count == user.posts.count\n# =&gt; true\ncloned.profile.name\n# =&gt; nil\n</code></pre>\n\n<p>Example copied from the project, but it will give a clear vision of what you can achieve.</p>\n\n<p><strong>For a quick and simple record I would go with:</strong></p>\n\n<p><code>Model.new(Model.last.attributes.reject {|k,_v| k.to_s == \'id\'}</code></p>\n'}, {'answer_id': 51925581, 'author': 'Zoran Majstorovic', 'author_id': 3452582, 'author_profile': 'https://Stackoverflow.com/users/3452582', 'pm_score': 2, 'selected': False, 'text': '<p>Here is a sample of overriding ActiveRecord <code>#dup</code> method to customize instance duplication and include relation duplication as well:</p>\n\n<pre><code>class Offer &lt; ApplicationRecord\n  has_many :offer_items\n\n  def dup\n    super.tap do |new_offer|\n\n      # change title of the new instance\n      new_offer.title = "Copy of #{@offer.title}"\n\n      # duplicate offer_items as well\n      self.offer_items.each { |offer_item| new_offer.offer_items &lt;&lt; offer_item.dup }\n    end\n  end\nend\n</code></pre>\n\n<p>Note: this method doesn\'t require any external gem but it requires newer ActiveRecord version with <code>#dup</code> method implemented</p>\n'}, {'answer_id': 54035727, 'author': 'Foram', 'author_id': 8649274, 'author_profile': 'https://Stackoverflow.com/users/8649274', 'pm_score': 3, 'selected': False, 'text': '<p>In Rails 5 you can simply create duplicate object or record like this.</p>\n\n<pre><code>new_user = old_user.dup\n</code></pre>\n'}, {'answer_id': 66943947, 'author': 'Sachin Singh', 'author_id': 13088705, 'author_profile': 'https://Stackoverflow.com/users/13088705', 'pm_score': 0, 'selected': False, 'text': "<p>Try rails's <code>dup</code> method:</p>\n<pre><code>new_record = old_record.dup.save\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/60033', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3764/']