Clone (a.k.a. duplicate) a Record
ruby-on-rails
Solution
Make sure the default cloned behavior works for you. the cloned record might actually be invalid according to your validation rules.
Try to use `@item.save!` instead of `@item.save` and check whether an exception is raised. You can also try the code directly in a console instance.
In Console I figured out that clone generates the copy without ID.
That's true. `#clone` actually creates a clone but doesn't save the record. This is why you need to call a save method in your action, which is what you actually do with
if @item.save # <-- here you save the record
flash[:notice] = 'Item was successfully cloned.'
else
flash[:notice] = 'ERROR: Item can\'t be cloned.'
end
Problem
I need to duplicate a record, with the same attributes of the original except ID of cource. I do: In the View: ``` <%= link_to "Duplicate", :action => "clone", :id => Some_Existing_ID %> ``` And in the Controller: ``` def clone @item = Item.find(params[:id]).clone if @item.save flash[:notice] = 'Item was successfully cloned.' else flash[:notice] = 'ERROR: Item can\'t be cloned.' end redirect_to(items_path) end ``` But nothing happens! In Console I figured out that clone generates the copy without ID. Any ideas ? *> BTW: I am running Rails 2.3.5 and Ruby 1.8