0

I want to duplicate my models 'Formulaire' and 'Question'. They have a has_may/belongs_to relation. I'm able to duplicate the first model but I have a " NoMethodError in FormulairesController#duplicate undefined method `save' for # " when I duplicate the second

My models :

Formulaire.rb

class Question < ActiveRecord::Base
 belongs_to :formulaire
 validates :nom, presence: true
end

Question.rb

class Formulaire < ActiveRecord::Base
 has_many :questions, dependent: :destroy
end

formulaire_controller.rb

def duplicate
 template = Formulaire.find(params[:id])
 @formulaire= template.dup
 @formulaire.save

 #for question in @formulaire.questions
 #  question.dup
 #  question.save
 #end

 template2 = Question.where(formulaire_id: 47)
 @question = template2.dup
 @question.save
 redirect_to @formulaire, notice: "Formulaire dupliqué"
end

def formulaire_params
      params.require(:formulaire).permit(:name, :description, 
              questions_attributes: [:id, :nom, :typequestion, :image, '_destroy', photos_attributes:[:id],
                  answers_attributes:[:id, :content,'_destroy']]) if params[:formulaire]

      #puts YAML::dump params
end

My view

formulaire/show.html.erb

    <li class="Dupliquer"><%= link_to 'Dupliquer', duplicate_formulaire_path(@formulaire)  %> </li>

routes.rb

 resources :formulaires do
   member do
     get 'duplicate'
   end
 end

Thank you

user9007028
  • 125
  • 1
  • 1
  • 14

1 Answers1

0

Here in stackoverflow, I found it here:

If you want to copy an activeRecord object you can use its attributes to create new one like

you can have an action in your controller which can be called on link,

def  create_from_existing
 @existing_post = Post.find(params[:id])
 #create new object with attributes of existing record 
 @post = Post.new(@existing_post.attributes) 
 render "your_post_form"
end

what's here: Rails clone copy or duplicate

I never used this gem, but it's for this, I'm going to leave it there and you'll see what you want.

https://github.com/amoeba-rb/amoeba

And also on reddit

 def clone
    @location = Location.find(params[:id]).dup
    ............
    render :new
end

link: https://www.reddit.com/r/rails/comments/6phfy4/form_how_to_implement_a_clone_action/

Elis Bresciani
  • 116
  • 3
  • 13