Rails: has_many through multiple models

Viewed 24

I am trying to access all the projects for which there are expenses from or payments to a given supplier.

class Project < ApplicationRecord  
  has_many :payments #, dependent: :destroy  
  has_many :expenses, dependent: :restrict_with_error  
  has_many :suppliers,-> { distinct }, through: :expenses
end
    
class Supplier < ApplicationRecord
   has_many :expenses, dependent: :destroy
   has_many :payments, dependent: :destroy    
   has_many :projects, through: :expenses
end

class Expense < ApplicationRecord 
  belongs_to :project
  belongs_to :supplier    #, optional: true 
end

class Payment < ApplicationRecord
  belongs_to :project
  belongs_to :supplier

  scope :belongs_to_project, -> (project_id) { joins(:project).where("projects.id = ?",  "#{project_id}")} 
end

What would be ideal is if I could do

class Supplier < ApplicationRecord
   has_many :projects, through: [:expenses, :payments]
end

but since that does not work, I have resorted to

def balances
    project_ids = @supplier.projects.pluck(:id)

    Project.all.each do |project|
      #if there are no expenses (project not in @supplier.projects) but there are payments to supplier for the project, append the project.id to project_ids
      if !project_ids.include? project.id and @supplier.payments.belongs_to_project(project.id).any?
        project_ids << project.id
      end
    end
    
    @projects = Project.find( project_ids )
    
 end

Is there a more elegant way to do this?

0 Answers
Related