Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.1rubygems

How do I stop a flash error message from showing on page load until after button is clicked in ruby on rails?


I'm trying to figure out a way to stop this flash message from showing on page load:

class SearchesController < ApplicationController

   def index

     @users = User.search params[:search]
     @default_image = "/assets/default_avatar.jpg"
     if @users.empty? || params[:search].blank? 
        flash[:error] = "Sorry no user(s) found!" if @users.empty?
        flash[:error] = "Please give us something to search for!" if params[:search].blank?
        render 'index'
     end    
   end
end

I understand why it's showing (obviously when page is visited the search params is blank already). There must be some trick in ruby on rails that I can use on this flash message to stop it from firing until search button is clicked e.g.

flash[:error] = "Please give us something to search for!" if params[:search].blank? after_get 

Bare in mind that was after_get was made up.

I'm sure someone out there has the answer for this.

I saw after_commit in the rails api but no example of how to use it in my situation or even if it's what I need.

Kind reards


Solution

  • A simple solution would be to add a hidden field to the search form and check if that value is present instead of the actual search-string.

    View

    <%= hidden_field_tag :searching, true %>
    

    Controller

    flash[:error] = "Please give us something to search for!" if params[:searching]