Methods for limiting the Rails render format to html

后端 未结 5 2032
没有蜡笔的小新
没有蜡笔的小新 2020-12-09 11:18

I have a Rails 2.1.2 site that only has html templates e.g. jobs.html.erb, so when I request a restful resource:

www.mysite.com/jobs/1

5条回答
  •  甜味超标
    2020-12-09 11:57

    You can use Rails Per-Action Overwrite feature. What's this? --> It’s also possible to override standard resource handling by passing in a block to respond_with specifying which formats to override for that action:

    class UsersController < ApplicationController::Base
    
      respond_to :html, :xml, :json
    
      # Override html format since we want to redirect to a different page,
      # not just serve back the new resource
      def create
        @user = User.create(params[:user])
        respond_with(@user) do |format|
          format.html { redirect_to users_path }
        end
      end
    end
    

    :except And :only Options

    You can also pass in :except and :only options to only support formats for specific actions (as you do with before_filter):

    class UsersController < ApplicationController::Base
      respond_to :html, :only => :index
      respond_to :xml, :json, :except => :show
      ...
    end
    

    The :any Format

    If you’re still want to use respond_to within your individual actions, use the :any resource format that can be used as a wildcard match against any unspecified formats:

    class UsersController < ApplicationController::Base
    
      def index
    
        @users = User.all
    
        respond_to do |format|
          format.html
          format.any(:xml, :json) { render request.format.to_sym => @users }
        end
      end
    end
    

提交回复
热议问题