2013-05-12 70 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