2013-06-29 46 views
5

我使用的活動資源,以從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 

當我把這個蘇氨酸::卷:: 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」錯誤,我想顯示在視圖中返回的哈希的內容。

+0

請讓我知道現在是否有意義? – sorabh

+0

您還沒有提出任何問題。您對發生的事情發表了幾個聲明 - 您能解釋一下是什麼錯誤,或者您需要幫助嗎?謝謝。 –

+0

哦,我真的很抱歉。讓我再次更新問題。 – sorabh

回答

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"] 
+1

你可以解釋更多關於它,我對軌道的一點理解,我認爲主動資源已經爲我做了。 – sorabh

15

,您可以更改的ActiveResource處理與

class YourModel < ActiveResource::Base 
    self.format = ::JsonFormatter.new(:collection_name) 
end 

JSON響應在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根元素。

+0

我使用這種方式,但在我的模型中有錯誤 未初始化的常量JsonFormatter –

+1

您需要手動要求或在config/application.rb中添加'config.autoload_paths + =%W(#{config.root}/lib)'' ' –

+0

感謝問題解決 –