【问题标题】:Active resource rails not fetching data活动资​​源轨未获取数据
【发布时间】:2021-02-05 07:24:26
【问题描述】:

这是活动的.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

我无法从正在使用的活动资源中获取数据。请告诉我 谢谢

【问题讨论】:

  • 请添加更多信息让我们回答这个问题

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-5 ruby-on-rails-6 activeresource


【解决方案1】:

我怀疑 ActiveResource 没有发出您期望的请求。您可以通过在 Rails 控制台中运行以下命令来获得一些清晰的信息:

Active.collection_pathActive.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 = nil)
      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,无需求助于猴子补丁。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多