Duplicate a row of a table in my database - Ruby on rails

1

When creating a new event I have an option that is enabled with a checkbox that is to duplicate a quote already made of another event already created, I display the list of which event I need to duplicate that quote, I have several tables where it is saved one of them is one called sections and I need to duplicate the rows that have that id which is identified by quotation_id to know what event it belongs to, what I have to do is make a query to that table read the rows that have that id that I need to duplicate, duplicate those rows (create new records in my row), but when duplicating them I need to change the quotation_id to the new event I'm creating.

I do not know if you explain me well. Any suggestions on how I could do it?

def duplicate_data
  if params[:showhide] == "1"
    event_selected = params[:event_id_select] #quotation_id
    event_current = Event.last.id #Id del nuevo evento que se esta creando

  end
end
    
asked by AlexCs 24.07.2018 в 18:26
source

1 answer

0

You can use the dup method to duplicate a record in the model, modify it and then save it in the database; for example, to duplicate a row in the model Section :

def duplicate_data
  if params[:showhide] == "1"
    dup_section = Section.find_by(quotation_id: params[:event_id_select]).dup
    dup_section.quotation_id = Event.last.id
    dup_section.save!
  end
end

The above code works for 1 record only, if you have many records, you can do the same but using a loop :

def duplicate_data
  if params[:showhide] == "1"
    sections = Section.where(quotation_id: params[:event_id_select])
    event_id = Event.last.id

    sections.each do |section|
      dup_section = section.dup
      dup_section.quotation_id = event_id
      dup_section.save!
    end
  end
end

For the example I use save! to generate an exception in case of error when saving; however, for a code in production it is generally better to use valid? and then save , avoiding the exception (and handling any possible data error).

    
answered by 29.07.2018 в 08:02