问题描述
我正在使用活动资源从 api 获取数据并显示它,
我的控制器 model.rb 有
I am using active resource to get data from an api and display it,
My controller model.rb has
class Thr::Vol::Dom < ActiveResource::Base
class << self
def element_path(id, prefix_options = {}, query_options = nil)
prefix_options, query_options = split_options(prefix_options) if query_options.nil?
"#{prefix(prefix_options)}#{collection_name}/#{id}#{query_string(query_options)}"
end
def collection_path(prefix_options = {}, query_options = nil)
prefix_options, query_options = split_options(prefix_options) if query_options.nil?
"#{prefix(prefix_options)}#{collection_name}#{query_string(query_options)}"
end
end
ActiveResource::Base.site = 'http://10.00.0.00:8888/'
self.format = :json
self.collection_name= "/vv/test/domains"
def self.find
x = superclass.find(:one, :from => '/vv/test/domains/2013-06-25T05:03Z')
x
end
end
当我调用这个 Thr::Vol::Dom.find 方法时,它返回以下错误:
When i call this Thr::Vol::Dom.find method it returns the following error:
ArgumentError: expected an attributes Hash,
got ["0.0.0.0", "1.1.1.1", "2.2.2.2", "3.3.3.3", "4.4.4.4"]
这个 api 应该提供这样的东西
The api is expected to feed something like this
{"abs.com":["0.0.0.0", "1.1.1.1", "2.2.2.2", "3.3.3.3", "4.4.4.4"]}
为了我打的电话.
API 返回正确的散列,但我猜活动资源无法正确读取它,它直接读取散列的键值对中的值.
The API returns the correct hash but i guess active resource is not able to read it properly, it is directly reading the value in the key-value pair of the hash.
我想修复这个ArgumentError"错误,我想在视图中显示返回的散列的内容.
I want to fix this "ArgumentError" error , i want to display the contents of the returned hash in the view.
推荐答案
您可以更改 ActiveResource 处理 json 响应的方式
You can change how ActiveResource handle json response with
class YourModel < ActiveResource::Base
self.format = ::JsonFormatter.new(:collection_name)
end
在lib/json_formatter.rb
class JsonFormatter
include ActiveResource::Formats::JsonFormat
attr_reader :collection_name
def initialize(collection_name)
@collection_name = collection_name.to_s
end
def decode(json)
remove_root(ActiveSupport::JSON.decode(json))
end
private
def remove_root(data)
if data.is_a?(Hash) && data[collection_name]
data[collection_name]
else
data
end
end
end
如果您传递 self.format = ::JsonFormatter.new(:categories)
,它将在您的 API 返回的 json 中查找并删除 categories
根元素.
If you pass self.format = ::JsonFormatter.new(:categories)
it will find and remove categories
root element in your json returned by your API.
这篇关于抱怨的活动资源需要散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!