简体   繁体   中英

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 custom 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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM