如何使用 Rails 通过 Web 服务以 JSON 格式公开数据?
-
09-06-2019 - |
题
有没有一种简单的方法可以使用 Rails 以 JSON 格式将数据返回到 Web 服务客户端?
解决方案
Rails 资源为您的模型提供了 RESTful 接口。让我们来看看。
模型
class Contact < ActiveRecord::Base
...
end
路线
map.resources :contacts
控制器
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
因此,这为您提供了一个 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
其他提示
Rails 的猴子补丁是你最关心的事情 #to_json
方法。
在我的脑海中,您可以对哈希、数组和 ActiveRecord 对象执行此操作,这应该涵盖您可能想要的大约 95% 的用例。如果您有自己的自定义对象,那么编写自己的对象就很简单 to_json
方法,它可以将数据塞入哈希中,然后返回 json 化的哈希。
有一个插件可以做到这一点,http://blog.labnotes.org/2007/12/11/json_request-handling-json-request-in-rails-20/
据我了解,这个功能已经在 Rails 中了。但是去看看那篇博客文章,里面有代码示例和解释。
ActiveRecord 还提供了与 JSON 交互的方法。要从 AR 对象创建 JSON,只需调用 object.to_json。要从 JSON 创建 AR 对象,您应该能够创建一个新的 AR 对象,然后调用 object.from_json..据我了解,但这对我不起作用。
不隶属于 StackOverflow