2010-11-22 34 views
0

我正在用Rails製作一個JSON API,除了當我使用respond_with自定義類(不是ActiveRecord繼承的類)之外,它似乎可以正常工作。如何在Rails 3中使用自定義類的respond_with?

這裏是我的類:

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正在讓我發瘋。

+0

做了一些清理,使其更具可讀性和問題的標題。 – 2010-11-22 21:06:06

+0

感謝您的幫助! – Danny 2010-11-22 21:17:24

回答

1
  1. 你的類應該響應to_json方法

  2. 顯然設置:在respond_with方法位置選項。 Rails嘗試從傳遞給方法的對象中創建平穩的路由,但由於您的對象不是資源,所以會引發錯誤。

0

我不知道如果這有助於但是我沒有看到的respond_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模板...不知道如果你把json模板留空如果它需要你的「JSONResponse」類...

只是一個想法...

+0

我有respond_to,我只是沒有顯示控制器的那一部分 – Danny 2010-11-22 23:26:02

相關問題