开发者

How do I use respond_with with custom classes in Rails 3?

I am making a JSON API with Rails and it seemed to work fine except for when I use respond_with custo开发者_高级运维m classes (not an ActiveRecord inherited one).

Here is my class:

class JsonResponse
  def initialize(data, status)
    @data = data
    @status = status
  end

  def as_json(options={})
    {
      :data => @data,
      :status => @status
    }
  end
end

which is a simple response wrapper. When I try doing this:

def create
  unless(Match.find_by_user_id(params[:user_id]))
    Match.create(:user_id => params[:user_id])
  end
  time_response = JsonResponse.new("5", "success")
  respond_with(time_response)
end

I get this error:

NoMethodError (undefined method `model_name' for JsonResponse:Class):
  app/controllers/matches_controller.rb:9:in `create'

Any ideas? respond_with is driving me crazy.


  1. Your class should response to to_json method

  2. Obviously set :location option in respond_with method. Rails try to create restful route from the object you pass to the method, but because your object is not resource, the error is raised.


I am not sure if this helps but I do not see respond_to... respond_with works together with respond_to...

 respond_to :html, :xml, :json 

This can be defined on Controller level

example:

 class UsersController < ApplicationController::Base

  respond_to :html, :xml, :json

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

  def create
    @user = User.create(params[:user])
    respond_with(@user, :location => users_url)
  end
end

and then you can define your json template... don't know if you leave the json template empty if it takes your "JSONResponse" class...

just a thought...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜