由于API没有返回ActiveResources期望的JSON,因此必须实现一个新的解析器。
class Postcode < ActiveResource::Base
self.site = "http://api.postcodeapi.nu/"
headers['Api-Key'] = "495237e793d10330c1db0d57db9d3c7e6e485af7"
self.element_name = ''
self.include_format_in_path = false
class PostcodeParser < ActiveResource::Collection
def initialize(elements = {})
@elements = [elements['resource']]
end
end
self._collection_parser = PostcodeParser
end
这应该适用于以下查询
Postcode.find('5041EB')
,但不适用于
Postcode.where(id: '5041EB')
。主要原因是API具有不同的参数键
id
。API文档参考
type
,但不起作用。
我不确定ActiveResources是否适合这种情况。