2013-03-23 43 views
1

HTML任何迴應我有這樣的代碼:如何禁止除控制器

def show 
    @attachment = Attachment.find(params[:id]) 

    respond_to do |format| 
    format.html 
    end 
end 

該代碼允許在JSON迴應,但呈現什麼。如何顯示任何其他請求除html外的自定義頁面?

回答

2

您可以使用format.any任何其他要求,除了HTML:

def show 
    @attachment = Attachment.find(params[:id]) 

    respond_to do |format| 
    format.html { render text: => 'This is html' } 
    format.any { render :text => "Only html is supported" } 
    end 
end 
+0

感謝。有更多的通用解決方案嗎?寫這行太繁瑣 – mystdeim 2013-03-23 10:24:35

2

嘗試:

before_filter do 
    render text: 'Wrong type', status: 406 unless request.format == Mime::HTML 
end 
2

,當你在你的config/routes.rb文件中定義它們可以限制你的路由的格式

scope :format => true, :constraints => {:format => :html} do 
    resources :attachments 
end 

定義您想要在其中限制其格式的所有路線 範圍。