How do I stop a flash error message from showing o

2019-08-29 12:39发布

问题:

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

回答1:

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]


回答2:

I can think of java script based solution, (but not rails)

  1. Print the rails flash message in a dev
  2. Keep that DEV hidden
  3. When user clicks the search button, just use a java script to display the DIV

I think this fits your requirement, and as far as I'm concern rails doesnt support your requirement out of the box

HTH



回答3:

If I understand correctly, you access the action 'index' either with a GET request (in this case you don't want the flash message), or with a POST form where the :search field is filled.

You can check if you're in a POST request with request.post? (also exists request.get?, request.put?, etc...)

class SearchesController < ApplicationController

  def index       
    @default_image = "/assets/default_avatar.jpg"
    if request.post? 
       @users = User.search params[:search]
       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? 
       end
    end    
  end
end

I removed the render 'index', I think it's useless.