2a01ae9942939ee2b3954a6727d2bb92

How to set custom type/format in controller's response_to?

2012-06-21 01:50:52 +0800tonytonyjanRuby on Rails 節點 中發起
最後由 匿名 於回應 , 164次閱讀

環境
* Rails 3.2.6
* Ruby 1.9.3p194

發現

class ThemesController < ApplicationController
  def show
  end
end

這樣的設定不管我的 URL 有什麼後綴,都會 render /views/themes/show.html.erb,例如:

http://localhost/items/1.json
http://localhost/items/1.xxx
http://localhost/items/1.custom_ext
...

遭遇麻煩
我喜要在後綴是 .json 的時候,執行 render :json=>@theme,其他則照常 render /views/items/show.html.erb,於是我做了改變:

respond_to do |format|
  format.json { render :json => @item}
  format.any {render}
end

當後綴是 .json 時,確實成功回傳了 JSON 資料,而後綴是 .xml.html 時,則會確實 render /views/items/show.html.erb

然而當我使用自訂的後綴時,例如 .xxx.ooo.custom_ext,卻會得到 406 Not Acceptable,查資料後發現是因為只有被允許的 MIME type 後綴才會被 format.any 接受。

暫時解法

class ItemsController < ApplicationController
  def show
    if params[:format].present? && params[:format] == "json"
      render :json => @item
    end
  end
end

這照著我的需求被執行了,而如果有兩個以上的格式:

class ItemsController < ApplicationController
  def show
    case params[:format]
    when "json" then render :json => @item
    when "xml" then render :xml => @item
    ...
    else render
    end
  end
end

我覺得這看起來並不會比 respond_to 差,也很易讀。

問題

1. 對於我的狀況是否有更好的解?
2. 如果 case 可以做到 respond_to 所有的事情,但反過來 respond_to 卻不行,有什麼理由可以說服我使用 respond_to 而不用 case 即可?

暫無回應。
需要 登入 後方可回應,如果你還沒有帳號按這裡 註冊