Duplicating a record in Rails 3

坚强是说给别人听的谎言 提交于 2019-11-29 10:01:22

If you want the clone action to allow the user to review the duplicate before it is saved (AKA created), then it is almost like the "new" action, except with filled in fields already.

So your clone method could be a modification of your new method:

def new
  @prescription = Prescription.new()
end
def clone
  @prescription = Prescription.find(params[:id]) # find original object
  @prescription = Prescription.new(@prescription.attributes) # initialize duplicate (not saved)
  render :new # render same view as "new", but with @prescription attributes already filled in
end

In the view, they can then create the object.

To do this, you're going to have to create a new instance of your Prescription class. "dup" works, but you're assuming it overwrites the existing record. Only methods that end with a bang(!) tend to do that.

Your code should be:

def clone
 @prescription = Prescription.find(params[:id])
 @new_prescription = @prescription.dup
 @new_prescription.save
end

or

def clone
 @prescription = Prescription.find(params[:id]).dup
 @prescription.save
end

This isn't testing for times when the :id isn't found.

I was looking for logic to clone an existing record. I had to modify the logic posted by ronalchn slightly because when it tried to execute the second statement of clone I got an mass assignment error because it tried to copy id, created_at, updated_at which are not included in my attr_accessible list. This is how I modified the logic to get it to work in my application using my model:

@old_event = Event.find(params[:id]) # find original object
@event = Event.new
@event.field_1 = @old_event.field_1 (statement for each field in attar_accessible)
render :new # render same view as "new", but with @prescription attributes already filled in
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!