Home > Software design >  Ruby on rails api flash messages
Ruby on rails api flash messages

Time:05-31

im making a rails api but only the back-end, I created validations and flash messages but they dont show up on insomnia, postman or console. Are flash messages only supposed to show up in the view of the api?

this is my controller code:

    @genre = Genre.create(genre_params)
    if @genre.valid?
      @genre.save
      flash[:notice] = 'The genre has been added successfully!'
      
      redirect_to genres_path
    else
      flash[:alert] = @genre.errors.full_messages
    end
    
  end ```

CodePudding user response:

flash is a special hash with a special life cycle, but otherwise it's not terribly complicated. It is a hash just like any other. It doesn't show up unless you print/puts/log/output it somewhere.

If you want it to show up in the (Rails) console, you need to output it to the console somewhere where it is valid (within its life cycle).

puts(flash.inspect)

More reading: https://www.rubyguides.com/2019/11/rails-flash-messages

CodePudding user response:

You can send a response in return to your client (eg. postman)

 data = { message: 'The genre has been added successfully!'}   
 
 render json: {
      success: true,
      data: data || nil,
    }, status: 'success'

or you can write some helper methods for the responses like this

  def send_response(obj = nil, message = nil, status = :ok)
    render json: {
      success: true,
      data: obj || nil,
      message: message || nil
    }, status: status
  end

and from controller,

send_response(data)
  • Related