ActiveResource multiple nested routes for model

343 Views Asked by At

I'm using ActiveResource to pull objects from an internal API

This API has the following(simplified):

class Project < ApplicationRecord
  has_many :contributions
  ...
end

class Contribution < ApplicationRecord
  belongs_to :project
  belongs_to :user
  ...
end

class User < ApplicationRecord
  has_many :contributions
  ...
end

and routes so contributions can only be created associated to a project

resources :projects, except: [:new, :edit] do
  resources :contributions, except: [:new, :edit, :destroy]
end

resources :users, except: [:new, :edit] do
  resources :contributions, only: [:index, :show]
end

resources :contributions, only: [:index, :show, :update]

Is it possible to submit a dynamic prefix so that I can hit these paths selectively? i.e. projects/:project_id/contributions on create, but /contributions on index (all).

EDIT:

My active resources all look like so:

class Contribution < ActiveResource::Base
  self.site = "#{base_url}/api/v1/"
  self.headers['Authorization'] = "Token token=\"#{TokenGenerator}\""
  ...
end

Not much customization there.

My biggest concern is the create post which I would like to always be nested inside a project.

At the moment I'm checking params in the /contributions route to see if there is any viable 'parent_id' in them, and figuring out if said parent exists.

I'm guessing the gem was not designed with the idea of a resource having multiple routes. I can always include:

class Project  ActiveResource::Base
  self.site = "#{base_url}/api/v1/"
  self.headers['Authorization'] = "Token token=\"#{TokenGenerator}\""
  ...
  def contributions
    Contributions.all(params: {project_id: id})
  end
end

inside Projects.rb and make sure the API controller knows how to handle parents if they exist, but only because I have access to the source of both the API and the consumer app.

worth asking too: Am I just over complicating this?

0

There are 0 best solutions below