respond_to only format.js for all mime types

孤街浪徒 提交于 2020-01-24 06:57:11

问题


I have a controller which respond_to format.js, however, most request assume the old format.html still exists and throws a 404 exception. How do I capture all MIME request on the controller and redirect them only to format.js?

Here's the current controller action

def search
  respond_to do |format|
    unless @search.nil?
      format.js { render :partial => '/search/search_form', :status => 200 }
    else
      format.js { render :partial => '/search/not_exist', :status => 500 }
    end
  end
end

I'm trying to do something like this, (I know this is invalid, just for demonstration).

def search
  respond_to(:html) do |format|
    unless @search.nil?
      format.js { render :partial => '/search/search_form', :status => 200 }
    else
      format.js { render :partial => '/search/not_exist', :status => 500 }
    end
  end
end

回答1:


If all requests should only be js, just take out the whole respond_to structure:

def search
  unless @search.nil?
    render :partial => '/search/search_form', :status => 200
  else
    render :partial => '/search/not_exist', :status => 422
  end
end

(note: change to 422 unprocessable entity to indicate a semantic problem with the submission. 500 is usually reserved for server errors, as in, crashes, stack dumps, etc)




回答2:


You can plug in a permanent redirect to your format.html and loop it back to the controller using the format you want. This is the way that you would redirect, say, an RSS feed to an atom feed or something where you may have multiple input formats, but only one output format

respond_to do |format|
...
format.js { do whatever }
...
format.html { redirect_to path_back_here(:format => :js) }

Replacing path_back_here with whatever path you are using ( search_path? )



来源:https://stackoverflow.com/questions/7056293/respond-to-only-format-js-for-all-mime-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!