如何在Rails 3中使用respond_with和自定义类?

时间:2010-11-22 19:05:12

标签: ruby-on-rails ruby ruby-on-rails-3

我正在使用Rails创建一个JSON API,除了我使用respond_with自定义类(不是ActiveRecord继承的类)时,它似乎工作正常。

这是我的班级:

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

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

这是一个简单的响应包装器。当我尝试这样做时:

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

我收到此错误:

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

有什么想法吗? respond_with让我发疯。

2 个答案:

答案 0 :(得分:1)

  1. 您的班级应该回复to_json方法

  2. 显然在respond_with方法中设置:location选项。 Rails尝试从传递给方法的对象创建restful路由,但由于您的对象不是资源,因此会引发错误。

答案 1 :(得分:0)

我不确定这是否有帮助,但我没有看到response_to ... respond_with与respond_to一起工作......

 respond_to :html, :xml, :json 

这可以在控制器级别

上定义

示例:

 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

然后你可以定义你的json模板...如果它需要你的“JSONResponse”类,不知道你是否将json模板留空......

只是一个想法...