主动资源抱怨期望哈希

我正在使用活动资源从api获取数据并显示它,
我的控制器model.rb有

class Thr::Vol::Dom < ActiveResource::Base class < '/vv/test/domains/2013-06-25T05:03Z') x end end 

当我调用此Thr :: Vol :: Dom.find方法时,它返回以下错误:

 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会提供类似这样的东西

 {"abs.com":["0.0.0.0", "1.1.1.1", "2.2.2.2", "3.3.3.3", "4.4.4.4"]} 

我做的电话。

API返回正确的哈希值,但我认为活动资源无法正确读取它,它直接读取哈希值的键值对中的值。

我想解决这个“ArgumentError”错误,我想在视图中显示返回的哈希的内容。

您可以更改ActiveResource处理json响应的方式

 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根元素。

API返回一个JSON对象,而不是Ruby哈希。 您需要使用Ruby的JSON模块将其转换为哈希:

 require 'JSON' hash = JSON.parse('{"abs.com":["0.0.0.0", "1.1.1.1", "2.2.2.2", "3.3.3.3", "4.4.4.4"]}') 

这将返回一个哈希,然后您会注意到键/值对将按预期工作:

 hash["abs.com"] => ["0.0.0.0", "1.1.1.1", "2.2.2.2", "3.3.3.3", "4.4.4.4"]