David Lyod
David Lyod

Reputation: 1438

Active Resource Nested Routes

Im currently trying to integrate with a third party API using active resource.

Ive completed a large amount of the work but am struggling with a single nested resource.

/company/:company_id/users/:id

I can retrieve the users from the company using

API::Company.find(124343).users

but any subsequent changes to a user will not save.

I know i have to play with the Base.site attribute to accept the argument, I just cannot find how to set the attribute. For example in the User record it has a company_id value. So obtaining the company_id is easy, I just cannot work out how to get the URL to contain it correctly and therefore its not going to the correct route, instead going to somewhere like

/company//users/32435

Upvotes: 2

Views: 996

Answers (2)

CaTs
CaTs

Reputation: 1323

Assuming you have a base class like:

class Base < ActiveResource::Base
  self.site = 'http://my.api.com/'
end

You can have a resource with a nested path using the prefix setter:

class User < Base
  self.prefix = '/companies/:company_id/'
end

# Do stuff ...

User.find(:all)                # => ActiveResource::MissingPrefixParam
User.find(:all, company_id: 5) # => GET https://my.api.com/companies/5/users
User.find(10, company_id: 5)   # => GET https://my.api.com/companies/5/users/10 

As usual the rails docs have lots of good info and examples: Active Resource Docs

Upvotes: 0

sorabh
sorabh

Reputation: 327

Try this

Class ABC
require "rubygems"
#This code block just makes sure not to append .json to the call
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

#Ur site url 
ActiveResource::Base.site = 'http://aaa:8080/'
self.format = :json
self.collection_name= "/company/"

def self.find(company_id, id)
  x = superclass.find(:all, :from => '/company/%s/users/%s' %[company_id,id])
  x
  end
end 

In your controller you will do

 @test=ABC.find(params[:customer_id],params[:id]) 

and this would return the data from api. Let me know if it works for you.

Upvotes: 1

Related Questions