Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 and JSON: Default renderer but custom mime type

Using ROAR ( https://github.com/apotonick/roar ) and without using ActiveRecord or any view-templates I want to:

  • use the default JSON rederer but my own mime type to render JSON with respond_with
  • use the default JSON parser but my own mime type to put entries of the POST-body into the params hash.

config/initializers/mime_types.rb:

Mime::Type.register "application/vnd.xxx-v1+json" , :xxx_v1

controllers/api/base_controller.rb

class Api::V1::BaseController < ActionController::Base
  respond_to :xxx_v1

  ActionController.add_renderer :xxx_v1 do |obj, options|
    json = obj.to_json
    self.content_type ||= Mime::Type.lookup('application/vnd.xxx-v1+json')
    self.response_body  = json
  end
end

controllers/api/user_controller.rb:

class Api::V1::UsersController < Api::V1::BaseController 

  def index
    respond_with User.all
  end
end

GET http://domain/users Accept application/vnd.xxx-v1

ERROR: Missing template api/v1/users/index, api/v1/base/index with {:handlers=>[:erb, :builder], :formats=>[:xxx_v1], :locale=>[:en, :en]}

After reading several posts like Rails Custom Renderer or rails 3 response format and versioning using vendor MIME type in the Accept header I still can't get it work..

-=== small update ===-

When I use render directly in the controller, it's working! Always problems with respond_with...

render :xxx_v1 => User.all
like image 683
Ginkgochris Avatar asked Jan 02 '12 11:01

Ginkgochris


1 Answers

Solution for rendering:

Put an empty method into your models:

def to_xxx_v1
end

It is not called but has to be present for respond_with.

like image 200
Ginkgochris Avatar answered Oct 26 '22 22:10

Ginkgochris