gpt4 book ai didi

ruby-on-rails - 提示的事件资源需要散列

转载 作者:行者123 更新时间:2023-12-03 17:50:56 25 4
gpt4 key购买 nike

我正在使用事件资源从 api 获取数据并显示它,
我的 Controller 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”错误,我想在 View 中显示返回的散列的内容。

最佳答案

您可以更改 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)它会找到并删除 categories API 返回的 json 中的根元素。

关于ruby-on-rails - 提示的事件资源需要散列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21588316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com