我的 Rails 5 应用程序中有一个搜索 Controller ,如果搜索词为空,我希望它返回状态为 400 的 header ,否则搜索并呈现结果页面。
这是我的 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
我试过调整 if 和 return 语法,但似乎没有任何效果。当我从没有搜索字符串的 View 中单击搜索按钮时,它只会在 Controller 路径下呈现一个空白页面。我希望它只停留在同一页面上,什么都不做。
最佳答案
实际上是在写
params.require(:search).permit(:search)
使 search
参数必须存在且不能为空。
为了让它工作,稍微改变它背后的逻辑,不要使用强参数(你手动检查它):
search_term = params[:search]
head 400 and return if search_term.blank?
search_term.downcase!
或者您可以利用该异常,改为编写:
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
但这可能被一些人认为是一种反模式。然而,我认为它在这里是合适的,而且实际上非常明确。
关于ruby-on-rails - 如何在不渲染其默认 View 的情况下从 Controller 操作返回头部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42974780/