Ruby on rails 如何从控制器动作返回头部而不呈现其默认视图?
我的Rails 5应用程序中有一个搜索控制器,如果搜索词为空,我希望它返回400状态的head,否则搜索并呈现结果页面 这是我的控制器Ruby on rails 如何从控制器动作返回头部而不呈现其默认视图?,ruby-on-rails,Ruby On Rails,我的Rails 5应用程序中有一个搜索控制器,如果搜索词为空,我希望它返回400状态的head,否则搜索并呈现结果页面 这是我的控制器 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 ?",
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语法,但似乎没有任何效果。当我在没有搜索字符串的视图中单击搜索按钮时,它只是在控制器路径下呈现一个空白页面。我希望它只是停留在同一页上,什么也不做。实际上是在写作
params.require(:search).permit(:search)
使搜索
参数必须存在且不为空
要使其工作,请更改其背后的一点逻辑,不要使用强参数(您正在手动检查):
或者,您可以利用该例外情况,改为编写:
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
但有些人认为这是一种反模式。然而,我认为它在这里是合适的,实际上非常明确。第一个示例并不能解决这个问题,它仍然在搜索路径下呈现一个空白页面。对于第二种解决方案,永远不会触发异常,所有记录都会返回到页面上<代码>它仍然在搜索路径下呈现一个空白页面——这看起来像是发送400个标题和空正文的完美示例。我在其他地方读到,浏览器假定类型2和4响应代码将与新页面一起呈现。我试着用303等等,但没有成功。使用
render:back
,我得到了一些接近我想要的东西,但是用户体验有点糟糕。我想我将构建一些Jquery并让Ajax处理它。
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