2013-05-12 28 views

回答

3

我有一個提議,雖然有點哈克恐怕:)

class < ApplicationController 
    before_filter :disable_json 

    def disable_json 
    if request.format =~ /json/ 
     //do something you like, redirect_to or reply with message 
    end 
    end 

的before_filter,來將任何特定的控制器的方法之前被解僱。

JSON的標題通常是 「應用/ JSON」

request,你可以在這裏閱讀更多:http://guides.rubyonrails.org/action_controller_overview.html#the-request-object

+0

其實這是一個非常好的解決方案,找不到任何更好的解決方法,謝謝:) – 2013-05-14 01:48:42

+0

@TamerShlash,我的榮幸:)不確定爲什麼你將操作符修改爲完全匹配,因爲格式可能包含除'json'之外的其他字符。我認爲REGEX比賽應該更好,並修改它。 – 2013-05-14 03:41:18

+0

它給了我一個錯誤,因爲它是'〜='not'=〜',我不知道是什麼問題,因爲我不熟悉Ruby Regex,再次感謝:) – 2013-05-14 03:49:07

1

你也可以做到這一點在routes.rb中,使用約束:

# Only allow HTML requests for all resources within the block 
scope constraints: {format: :html} do 
    resources :posts 
    resources :comments 
    get "/profile", to: "users#profile" 
end