Avoid process using before_action

0

I am developing the user permissions and I am trying to use a before_action to evaluate a conditional, if it returns false I want the "create" action not to execute, but if it returns true the record will be created

this would be my before_action:

before_action :permiso_create, only: [:create]

def create
  @producto = Producto.new(producto_params)
  respond_to do |format|
    if @producto.save
      format.html { redirect_to @producto, notice: 'Producto was successfully created.' }
      format.json { render :show, status: :created, location: @producto }
      format.js {flash.now[:notice] = 'El producto se ha creado de forma exitosa.'} #ajax
    else
      format.html { render :new }
      format.json { render json: @producto.errors, status: :unprocessable_entity }
      format.js {flash.now[:alert] = 'Error al crear el producto.'} #ajax

    end
  end
end

if the conditional returns true that the record is not created or the create action is not executed, showing a flash alert with the message "permission denied"

I have tried with unprocessable_entity but it does not return the message, stopping the process before showing it, like this:

def permiso_create
  @puede_crear = current_usuario.profiles.find_by_Descripcion("products").Altas
  if @puede_crear != true
      respond_to do |format|
        format.js {flash.now[:alert] = 'you don't have permission.'}
      end
     head :unprocessable_entity

  end
end

in what way could I avoid creating and sending that message? thanks in advance.

    
asked by jeff 25.09.2017 в 18:21
source

1 answer

0

For the callback to stop the execution of the action, you must call render or redirect_to ; in your case it would be best to use render ; for example:

def permiso_create
  @puede_crear = current_usuario.profiles.find_by_Descripcion("products").Altas

  unless @puede_crear
    flash.now[:alert] = 'you don't have permission.'
    render 'new'
  end
end

Notes:

  • != true is not necessary, you can simply use !@puedes_cerar to deny the evaluation, or better yet (and as I show in the example), you can use unless .

  • I used the action new assuming that the user comes from there, but adjusts the code to be the correct view.

  • I removed format.js (in fact the whole%% block) since it seems that you are looking for a respond_to message, but in case you need to use flash , you can simply use js , where render js: 'new' corresponds to the javascript view (eg new ) you want to display.

answered by 25.09.2017 в 20:39