views:

31

answers:

1

I want to create a new instance of a model, however I want to bring some parameters from a different record also, essentially duplication most of the parameters into the new instance but leaving some fields blank as well.

Cloning it works (thanks @weppos)

# class RecipesController
def new
  @parent = Recipe.find(params[:parent_id])
  @recipe = @parent.clone
end

And while this does work, it breaks all my nested attributes:

# class Recipe
accepts_nested_attributes_for :ingredients, :reject_if => lambda { |a| a.values.all?(&:blank?) }, :allow_destroy => true

Like it only saves the new attributes and throws all the old ones away, the ones that should have been duplicated from the other instance.

+1  A: 

Use the clone method.

@parent = Recipe.find(params[:parent_id])
@recipe = @parent.clone

If the clone behavior doesn't apply to your need, then you can create a custom method starting from #clone then unsetting all unnecessary properties.

Simone Carletti
hmmm... clone worked perfectly, however it didn’t clone any of my nested attributes. Is it related to this bug > https://rails.lighthouseapp.com/projects/8994/tickets/3391-nested-attributes-vs-before_save
Joseph Silvashy