This blog post will answer the following issue common to almost all gui. In order to facilitate the life of the administrator, we often see the possibility to duplicate an existing record instead of creating a new one from scratch.
Before rails 3.1, this action was performed using the active-record clone method.
Rails 3.1 is introducing the dup method. Just by it's name, it seems to be the perfect candidate for our task.
How to use it ?
First let's test in the console:
rails c
a = Model.first # finds the first instance of the model "Model"
b = a.dup # duplicates the record
b.save # saves the record into the database.
If you look into your database, you can see that a new record has been created. It is identical to the first record excepted that it has a new id.
You can also modify one of the field of the model to show to the user that he is working with a duplicate and that he has to edit it. I usually prefix the name with "dup_" so I get "dup_Georges" indicating that I need to modify the record.
b.name = "dup_" + b.name
That's it. A simple but very useful method. In my opinion it's the 8th method that has been forgotten in the crud scaffold.
Some details about the implementation:
# ActiveRecord::Base#dup and ActiveRecord::Base#clone semantics have changed to closer match normal Ruby dup and clone semantics.
# Calling ActiveRecord::Base#clone will result in a shallow copy of the record, including copying the frozen state. No callbacks will be called.
# Calling ActiveRecord::Base#dup will duplicate the record, including calling after initialize hooks. Frozen state will not be copied, and all associations will be cleared. A duped record will return true for new_record?, have a nil id field, and is saveable.
2 comments:
it’s a great information.
duplicate cleaner
Really nice blog post. provided a helpful information. I hope that you will post more updates like this Ruby on Rails Online Course India
Post a Comment