0

EDIT : I'm using Mongoid, so no chaining nor has_many through:

I am developing a backend for project administration, and I have "deeply" related models

class Project
  include Mongoid::Document
  has_many :steps
  scope :active, ...

class Step
  has_many :assignments

class Assignment
  belongs_to :contractor, inverse_of: :project_assignment
  belongs_to :step

class Contractor
  belongs_to :user, inverse_of: :contractor_profile
  has_many :project_assignments, class_name: 'Assignment'

class User
  has_one :contractor_profile, class_name: 'Contractor'

Now, I have coded a sidebar for my users. In this sidebar, If the User has a contractor profile, I want to display the number of active projects

What would be the best way to implement an access to this information ?

We're talking about maybe up to 30 active projects at a time, from 1 to 6 assignments per project (but many steps with same contractors), and contractors usually have a few projects total (active or not).

My ideas :

  • Look at the current_contractor assignments -> steps -> projects -> count active ones
  • Look at active projects -> assignments -> Find contractors which match current_contractor
  • Maybe add a belong_to :project (how can I ensure it's the same as self.step.project ?) in every Assignment to be able to jump Contractor -> assignments -> projects & count
Cyril Duchon-Doris
  • 12,964
  • 9
  • 77
  • 164

1 Answers1

-2

Not sure if about how you are using a presenter or a view directly, but from a model perspective, you should be able to do it chaining the activerecord associations (which it sounds like you already have in mind). For example

current_contractor.assignment.steps.projects.where(:status=>'active').count

You could refine this a little by making an active/inactive scope in the Projects model so then it would be

current_contractor.assignment.steps.projects.active.count

If this type of query is likely to be common, I'd consider creating a nested has_many_through relationship to go from contractor to projects, for example in the Contractor definition:

has_many :steps, 
       :through => :assignments
has_many :projects, :through => :steps

Then you could just do

contractor.projects.count

or if you've created the Project active/inactive scopes

contractor.projects.active.count

Hope that helps

jezpac
  • 1
  • Oh sorry, I added the tag, but forgot to mention it in the post. I'm using Mongoid not ActiveRecord, so no `has_many :through` :(. And no, unfortunately, I cannot chain associations. If I do `current_contractor.assignments.steps` I get a `ActionView::Template::Error (undefined method 'assignments' for #):` – Cyril Duchon-Doris Apr 30 '15 at 12:56
  • This solution uses invalid syntax and association calls. – Dan L Aug 18 '15 at 16:57