0

我正在使用 Rails 中的 API 来响应 xml 和 json。除了 1 个动作,xml 和 json 都按预期响应。在 total_words 操作中,它正确响应 json 而不是 xml。

pages_controller.rb

class Api::PagesController < ApplicationController
  respond_to :json, :xml

  def index
    @pages = Page.all
    respond_with @pages
  end

  def show
    @page = Page.find(params[:id])
    respond_with @page
  end

  def total_words
    @page = Page.find(params[:id])
    respond_with @page.words
  end
end

页面.rb

class Page < ActiveRecord::Base
  attr_accessible :content, :published_on, :title

  validates :title, :presence => true, :uniqueness => true
  validates :content, :presence => true


  def words
    self.content.split.size
  end

end

路由.rb

API::Application.routes.draw do

  match 'api/pages/:id/total_words' => 'api/pages#total_words', :as => "total_word_api_page"

  namespace :api do
    resources :pages
  end

end

如果我通过 curl 使用:

curl --url http://0.0.0.0:3000/api/pages/3/total_words.xml

我什么都得不到。

如果我通过 curl 使用:

curl --url http://0.0.0.0:3000/api/pages/3/total_words.json

我得到:3

如果我通过浏览器访问:

http://0.0.0.0:3000/api/pages/3/total_words.xml

我得到:

Template is missing

Missing template api/pages/total_words, application/total_words with {:locale=>[:en], :formats=>[:xml], :handlers=>[:erb, :builder, :coffee]}. Searched in: * "/api_test/API/app/views"

如果我在浏览器中做同样的事情但使用 json 我会得到: 3 就像我在 curl 中所做的一样。

我不确定为什么 json 和 xml 响应不同。

4

1 回答 1

0

问题似乎是我试图返回一个与 json 一起使用但不是 xml 的整数或字符串。我将返回值修改为哈希值,json 使用 json 和 xml 成功返回了正确的值。看起来 xml 可以使用数组或散列。

我现在修改的方法是:

  def words
    { id: self.id, word_count: self.content.split.size }
  end
于 2013-06-01T01:03:44.490 回答