Skip to content

Using custom responder

ccocchi edited this page Sep 24, 2012 · 1 revision

When using Rails default responder, POST and DELETE action will use to_#{format} to render default response.

class PostsController < ApplicationController
 respond_to :json

 def create
  @post = Post.new(params[:post])
  @post.save
  respond_with @post
 end
end

For example if you try to create a Post via JSON, Rails will call @post.to_json as a response. This is very annoying and most of the time you want to render the show (or any other) template of your newly created object. Using rabl-rails custom responder will ensure that.

Add this to your configuration file to enable it

RablRails.configure do |c|
 c.use_custom_responder = true
 # c.responder_default_template = 'show'
end

The second option can be used to change the default template rendered by default. This template can also be set per controller. If we take our previous controller, just add a responder_default_template method to choose a different template

class PostsController < ApplicationController
 ...

 protected
 def responder_default_template
  'base'
 end
end
Clone this wiki locally