Ruby/Rails playing with arrays from multilevel nested associations

73 views Asked by At

I have nested models, all mongoid documents :

class Project { ... has_many :tasks ...}

class Task 
  ... 
  has_many :attributions, class_name: "TaskAttribution"
  belongs_to :project

class TaskAttribution 
  ...
  belongs_to :task 
  belongs_to :user 

I want to get an array of all TaskAttribution from a given project.

I'm sure I can do it with

class Project
  ...
  def attributions
    attris = Array.new
    self.tasks.each do |task|
      task.attributions.each do |attri|
        attris << attri
      end
    end
  end

Is the compiler doing any improvements, or should I manually do some eager loading ?

Same thing with an extra level of nesting ? (If I want an array of every user participating to the project)

class Project
  ...
  def participating_users
    users = Array.new
    self.tasks.each do |task|
      task.attributions.each do |attri|
        attris << attri.user
      end
    end
    users.uniq
  end

EDIT : removed other questions because they were judged too subjective/not in the spirit of StackOverflow

0

There are 0 answers