method

respond_with

Importance_5
v3.0.0 - Show latest stable - 4 notes - Class: ActionController::MimeResponds
respond_with(*resources, &block) public

respond_with wraps a resource around a responder for default representation. First it invokes respond_to, if a response cannot be found (ie. no block for the request was given and template was not available), it instantiates an ActionController::Responder with the controller and resource.

Example

  def index
    @users = User.all
    respond_with(@users)
  end

It also accepts a block to be given. It’s used to overwrite a default response:

  def destroy
    @user = User.find(params[:id])
    flash[:notice] = "User was successfully created." if @user.save

    respond_with(@user) do |format|
      format.html { render }
    end
  end

All options given to respond_with are sent to the underlying responder, except for the option :responder itself. Since the responder interface is quite simple (it just needs to respond to call), you can even give a proc to it.

Show source
Register or log in to add new notes.
October 16, 2010 - (>= v3.0.0)
12 thanks

needs to be paired with respond_to

Needs to be paired with respond_to at the top of your class.

class MyController < ApplicationController
  respond_to :js, :html
October 8, 2011
6 thanks

Undocumented :location option

You can use undocumented :location option to override where respond_to sends if resource is valid, e.g. to redirect to products index page instead of a specific product’s page, use:

respond_with(@product, :location => products_url)  
June 24, 2011 - (v3.0.0 - v3.0.9)
1 thank

RailsCast about Responders

See Ryan Bate’s excellent RailsCast #224 about Responders in Rails 3.x: http://asciicasts.com/episodes/224-controllers-in-rails-3

June 1, 2014 - (v4.0.2)
1 thank

Alternitive to to add flash to respond with

This is a nice way to add flash if you don’t have a any logic that needs to go around your flash.

def destroy
  @current_user_session.destroy
  respond_with @current_user_session do |format|
    format.html {redirect_to login_path, notice: "You have been logged out"}
  end
end