ruby-on-railsstrong-parametersdragonfly-gem

param is missing or the value is empty: gallery


The problem is with "strong parameters" in rails. I use dragonfly for uploading images.

The problem is that if I send an empty form I do not get any parameters for error handling. What can be the reason?

Controller:

There is still also a method "Create" which saves the image in the database and sends the user to a page with pictures.

def index
  @gallery = Gallery.new
  @galleries = Gallery.all
end

def create
  @gallery = Gallery.new(gallery_params)

  if @gallery.save
    redirect_to galleries_path, flash: { success: 'Your Image was successfully save.' }
  else
    redirect_to :back,          flash: { alert: "Your Image don't save." }
  end
end

def gallery_params
  params.require(:gallery).permit(:image)
end

Views:

= form_for @gallery do |f|
  = f.file_field :image
  = f.submit 'Submit', class: 'btn bth-primary btn-lg'

Parameters:

{"utf8"=>"✓",    "authenticity_token"=>"8eotQtkj8SElqJLdHuOX8r+dWrCJRWTmVcyfd1mSLD/8MjWw/ElH/HCxZFSJ6oOWaxpbLbn4kAg5nlFycsgjHg==", "commit"=>"Submit"}

Solution

  • This is the expected behavior, see the documentation for ActionController::Parameters#require

    What I usually do in those cases is catch the exception and display a flash message to notify the user. You could also manually add an error to the model.

    def create
      @gallery = Gallery.new(gallery_params)
    
      if @gallery.save
        redirect_to galleries_path, flash: { success: 'Your Image was successfully save.' }
      else
        redirect_to :back, flash: { alert: "Your Image don't save." }
      end
    rescue ActionController::ParameterMissing => e
      redirect_to :back, flash: { alert: "Please attach an image." }
    end