Note that there are some explanatory texts on larger screens.

plurals
  1. PODuplicating a record in Rails 3
    text
    copied!<p>I have a prescription model in my Rails 3 application. I am trying to work out the best method of allowing records to be duplicated, but allowing the user to "review" the duplicate before it's saved.</p> <p>I have read a number of questions/answers on SO (such as <a href="https://stackoverflow.com/questions/2070250/clone-a-k-a-duplicate-a-record">this</a> one) which explain how to duplicate/clone the record and then save it - but none which explain how to show the form before save.</p> <p>Reading the Rails API is appears the <a href="http://edgeapi.rubyonrails.org/classes/ActiveResource/Base.html#method-i-clone" rel="nofollow noreferrer">clone</a> method is available.</p> <p>Reading <a href="https://stackoverflow.com/questions/60033/what-is-the-easiest-way-to-duplicate-an-activerecord-record?lq=1">other questions</a> and answers shows that is can be done but there is no example code apart from:</p> <pre><code>new_record = old_record.dup </code></pre> <p>The controller code I am currently working with is as follows (the model doesn't have any relationships):</p> <pre><code> # POST /prescriptions # POST /prescriptions.json def create @prescription = Prescription.new(params[:prescription]) @prescription.localip = request.env['REMOTE_ADDR'] @prescription.employee = @prescription.employee.upcase respond_to do |format| if @prescription.save format.html { redirect_to @prescription, notice: 'Prescription was successfully created.' } format.json { render json: @prescription, status: :created, location: @prescription } else format.html { render action: "new" } format.json { render json: @prescription.errors, status: :unprocessable_entity } end end end </code></pre> <p>I am going to be linking to this clone action from the view with:</p> <pre><code>&lt;%= link_to "Create another like this?", clone_prescription_url(@prescription), :method =&gt; :put %&gt; </code></pre> <p>Is it as simple as adding an action to my controller like this?</p> <pre><code>def clone @prescription = Prescription.find(params[:id]) @prescription.dup @prescription.save end </code></pre> <p>Apologies if the above code is completely wrong, I'm trying to get my head around it! I've seen <a href="https://stackoverflow.com/questions/8555488/rails-duplicate-record-not-rendering-new?rq=1">someone</a> do exactly what I'm trying to achieve with the cloning - but not with the editing before save.</p> <p>The user that's duplicating won't have permission to edit a record once saved. It's purely for the intial data entry.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload