ruby-on-railsruby-on-rails-3ruby-on-rails-5ruby-on-rails-6activeresource

Active resource rails not fetching data


This is 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

I am Unable to fetch data from the using active resource. Please let me know Thank you


Solution

  • I suspect that ActiveResource is not making the request you are expecting. You can get some clarity by running the following in the Rails console:

    Active.collection_path and Active.element_path

    for the former you will see "/api/v1/users/actives.json" as activeresource expects the class Active to be the name of your resource.

    You can control the URI generated and remove the resource specification (ie .json) by overriding two of the ActiveResource methods

    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
    

    This would then give you a collection path of /api/v1/users

    Perhaps a cleaner option would be to use self.element_name = "users", the documentation indicates that this " In the case where you already have an existing model with the same name as the desired RESTful resource"

    You can also remove the format (.json) by using self.include_format_in_path = false as mentioned here.

    So you could have the same affect by using:

    class Active < ActiveResource::Base
      self.include_format_in_path = false
      self.site = "http://localhost:3002/"
      self.prefix = "/api/v1/"
      self.element_name = "users"
    end
    

    Just as an aside I'd like to link to this answer which has some extremely useful notes on customising ActiveResource without recourse to monkey patching.

    Also, you can override the logger so you can view details of the request. Spin up rails c and add ActiveResource::Base.logger = ActiveRecord::Base.logger now you can run Active.all and see the detail of the activeresource fetch.