6

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

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 方法时,它返回以下错误:

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”错误,我想在视图中显示返回的哈希的内容。

4

2 回答 2

17

您可以更改 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

如果您通过它,它将在您的 API 返回的 json 中self.format = ::JsonFormatter.new(:categories)查找并删除根元素。categories

于 2013-06-29T11:19:15.517 回答
0

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"]
于 2013-06-29T10:22:32.460 回答