Skip to main content

Nested has many through... Or is there a better way?

Rails • Asked by Stephen Sizer

Hi I have 2 models Tender and Group shown below.

For a Tender you can add Contractors (contractor_details) and you can also add Groups (groups). Groups also contain contractor_details.

This is so that they may want to categorize certain contractors they use alot into specific groups by speciality e.g. Joiners, Electrians e.t.c..

What would the best way for me to check all contractors added to a tender including through groups, this is so that I can then do authorization and only allow those contractors added to view the tender page?

class Group < ApplicationRecord
  belongs_to :company_detail
  has_many :group_contractors, dependent: :destroy
  has_many :contractor_details, through: :group_contractors
  has_many :tender_groups
  has_many :tenders, through: :tender_groups

  accepts_nested_attributes_for :group_contractors

  validates :name, presence: true
end
class Tender < ApplicationRecord
  belongs_to :user
  belongs_to :company_detail
  has_many :questions
  has_many :assets
  has_many :tender_groups, dependent: :destroy
  has_many :groups, through: :tender_groups
  has_many :tender_contractors, dependent: :destroy
  has_many :contractor_details, through: :tender_contractors
  has_many :bids

  accepts_nested_attributes_for :tender_groups
  accepts_nested_attributes_for :tender_contractors
  accepts_nested_attributes_for :assets

  validates :title, :length_days, :summary, presence: true  

end

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 22,346+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.