简体   繁体   English

如何在不显示默认视图的情况下从控制器操作返回头部?

[英]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. 我在我的Rails 5应用程序中有一个搜索控制器,如果搜索项为空白,我希望它返回一个400状态的头,否则搜索并呈现结果页面。

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. 我已经尝试调整if和return语法,但似乎没有任何效果。 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. 使search参数必须存在而不是空白。

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. 但是我认为这在这里是合适的,实际上非常明确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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