Duplicate a record with a folder attachment

I create an action that duplicates an element and then allows the user to edit it and save it back to the database.

I wrote the following method in my controller, and it basically works separately from the Paperclip application, which for some reason will not move.

def duplicate
  existing_event = Event.find(params[:id])
  @event = Event.new(existing_event.attributes)

  render action: 'new'
end

I saw this question where a person uses .dup, but I can’t get him to work in a situation where the user edits a new one before saving.

I also tried using something like @event.image = existing_event.image, but that also had no effect.

Here's what my creation method looks like:

def create
  @event = Event.create(event_params)

  if @event.save
    redirect_to events_path, notice: "Event was successfully created."
  else
    render action: 'new'
  end
end

If that matters, I use S3 to upload images, and it doesn't really matter to me if there are multiple copies of the image.

- ? !

+4
2

: .
.
, , , , .

new :

existing_event = Event.find(params[:id])
@event = Event.new(existing_event.attributes)

@event.image = File.open(existing_event.image.path,'rb')

render :action => 'new'

:
create, , create save - . @event=Event.new(event_params), if @event.save.

+3

, :

module Paperclip
  class HasAttachedFile
    def define_with_extensions
      define_without_extensions
      define_dup_override
    end

    alias_method_chain :define, :extensions

    private

    def define_dup_override
      name = @name
      @klass.send :define_method, "dup" do
        copy = super()
        self.class.attachment_definitions.each do |name, options|
          ivar = "@attachment_#{name}"
          copy.instance_variable_set(ivar, nil)

          copy.send(name).assign send(name)
        end

        copy
      end
    end
  end
end

, , .

+2

Source: https://habr.com/ru/post/1539314/


All Articles