如何使用Rails通过Web服务以JSON格式公开数据?

Adr*_*ila 6 json web-services ruby-on-rails

有没有一种简单的方法可以使用Rails将数据返回到JSON中的Web服务客户端?

Jas*_*Ong 10

Rails资源为您的模型提供RESTful接口.让我们来看看.

模型

class Contact < ActiveRecord::Base
  ...
end
Run Code Online (Sandbox Code Playgroud)

路线

map.resources :contacts
Run Code Online (Sandbox Code Playgroud)

调节器

class ContactsController < ApplicationController
  ...
  def show
    @contact = Contact.find(params[:id]

    respond_to do |format|
      format.html 
      format.xml {render :xml => @contact}
      format.js  {render :json => @contact.json}
    end
  end
  ...
end
Run Code Online (Sandbox Code Playgroud)

因此,这为您提供了API接口,而无需定义特殊方法来获取所需的响应类型

例如.

/contacts/1 # Responds with regular html page

/contacts/1.xml # Responds with xml output of Contact.find(1) and its attributes

/contacts/1.js # Responds with json output of Contact.find(1) and its attributes
Run Code Online (Sandbox Code Playgroud)