如何解决活动资源导轨未获取数据
这是 active.rb
class Active < ActiveResource::Base
self.site = "http://localhost:3002/api/v1/users" # **When i run this it is not fetching data**
self.site = Net::HTTP.get(URI.parse("http://localhost:3002/api/v1/users")) # **When i run this i can see the data in console. Will get error Bad URI**
end
welcome_controller.rb
def index
@active = Active.all
end
我无法从正在使用的活动资源中获取数据。请告诉我 谢谢
解决方法
我怀疑 ActiveResource 没有发出您期望的请求。您可以通过在 Rails 控制台中运行以下命令来获得一些清晰的信息:
Active.collection_path
和 Active.element_path
对于前者,您将看到 "/api/v1/users/actives.json"
,因为 activeresource 期望类 Active 是您的资源的名称。
您可以通过overriding two of the ActiveResource methods
控制生成的URI并删除资源规范(即.json)class Active < 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)}#{id}#{query_string(query_options)}"
end
def collection_path(prefix_options = {},query_options = split_options(prefix_options) if query_options.nil?
"#{prefix(prefix_options)}#{query_string(query_options)}"
end
end
self.site = "http://localhost:3002/"
self.prefix = "/api/v1/users"
end
这会给你一个 /api/v1/users
也许更简洁的选择是使用 self.element_name = "users"
,documentation 表示这“如果您已经拥有与所需 RESTful 资源同名的现有模型”
您还可以通过将 self.include_format_in_path = false
用作 mentioned here 来删除格式 (.json)。
所以你可以通过使用:
class Active < ActiveResource::Base
self.include_format_in_path = false
self.site = "http://localhost:3002/"
self.prefix = "/api/v1/"
self.element_name = "users"
end
顺便说一句,我想链接到这个答案,其中有一些非常有用的notes on customising ActiveResource,无需求助于猴子补丁。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。