"Object-Oriented Swift" was retired on May 31, 2020. You are now viewing the recommended replacement.

Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Patrick Montalto
Patrick Montalto
7,868 Points

Duplicating record as default fields in form

I have an object called Formula which can serve as a Master Formula to many Child Formulas.

I want to create a link to "Create Child Formula" on the Master Formula's show page. I did so as follows:

<%= link_to 'Create Child', new_formula_path(:command => "create child", :parent_id => @formula.id) %> 

And in my FormulaController I have:

def new
    if params[:command].blank?
      @formula = Formula.new
      @formula.formulation_line_items.build
    elsif params[:command] == "create child"
      @formula = Formula.find(params[:parent_id])
    end
end

And it successfully renders the new page with the form filled-out with the Master's data, allowing the user to edit whichever fields they need.

But without Formula.new under the "create child" branch, it only accepts the form as an Update and not a Creation. (it's the new action and renders new.html.erb, but form button is for Update Formula).

How can I solve this problem? Is there just a way to force POST instead of PATCH so the button creates a new record instead of updating the existing one?

1 Answer

You can use the dup method on a model instance to create a copy of it which can then be manipulated (by editing the form) and saved as a new record.

  @formula = Formula.find(params[:parent_id]).dup

This is just a shallow copy however as stated in the documentation:

Duped objects have no id assigned and are treated as new records. Note that this is a “shallow” copy as it copies the object’s attributes only, not its associations. The extent of a “deep” copy is application specific and is therefore left to the application to implement according to its need. The dup method does not preserve the timestamps (created|updated)_(at|on).