简体   繁体   中英

How can you return a head from a controller action without rendering its default view?

I have a search controller in my Rails 5 app, and I would like for it to return a head with 400 status if the search term is blank, but otherwise search and render the results page.

Here is my controller...

def new
  search_term = search_params[:search].downcase
  head 400 and return if search_term.blank?

  @search_results = Post.where("lower(title) LIKE ? OR link LIKE ?",
                               "%#{search_term}%",
                               "%#{search_term}%").
                         order("created_at DESC").
                         paginate(page: params[:page], per_page: 30)
  if @search_results.empty?
    flash.now[:information] = "No results found"
  end
end

private

  def search_params
    params.require(:search).permit(:search)
  end

I've tried adjusting the if and return syntax, but nothing seems to work. When I click the search button from the view with no search string, it just renders a blank page under the controllers path. I want it to just stay on the same page and do nothing.

Actually writing

params.require(:search).permit(:search)

makes search params required to be present and not be blank.

To make it work change a little bit logic behind it and don't use strong parameters (you're checking it manually):

search_term = params[:search]
head 400 and return if search_term.blank?
search_term.downcase!

Or you can take advantage of that exception, by writing instead:

rescue_from ActionController::ParameterMissing, with: :render_error

def new
  search_term = search_params[:search].downcase!
  (rest of your code)
end

protected

def render_error
  head 400
end

but this can be considered an anti pattern by some. However I believe it's appropriate here and actually quite explicit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM