Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join Table issue with rails 6

I have a Color model: 

class Color < ApplicationRecord
  belongs_to :sector

A sector model:

class Sector < ApplicationRecord
  has_many :colors

I created a join table like:

class CreateJoinTableColorSector < ActiveRecord::Migration[6.0]
  def change
    create_join_table :color, :sectors do |t|
      t.index %i[color_id sector_id]
      t.index %i[sector_id colore_id]
   end
 end
end 

Now I want to get all the Colors who belongs to a specific sector. I tried :

Color.joins(:sectors).where({ sector: sector })

But it returns me an error → uninitialized constant Color::Sectors

like image 477
Xavier Avatar asked Dec 11 '25 03:12

Xavier


1 Answers

If you have a Color model like:

# == Schema Information
#
# Table name: colors
#
#  id           :integer          not null, primary key
#  created_at   :datetime         not null
#  updated_at   :datetime         not null
#
class Color < ApplicationRecord
  has_many :color_sectors
  has_many :sectors, through: :color_sectors  
end

And a Sector model like:

# == Schema Information
#
# Table name: sectors
#
#  id           :integer          not null, primary key
#  created_at   :datetime         not null
#  updated_at   :datetime         not null
#
class Sector < ApplicationRecord
  has_many :color_sectors
  has_many :colors, through: :color_sectors
end

Then you create your ColorSector model like:

# == Schema Information
#
# Table name: color_sectors
#
#  id           :integer          not null, primary key
#  color_id     :integer
#  sector_id    :integer
#  created_at   :datetime         not null
#  updated_at   :datetime         not null
#
class ColorSector < ApplicationRecord
  belongs_to :color
  belongs_to :sector
end

And when you have an @color and you want to get all the associated Sector records, you can do:

@color.sectors

And when you have an @sector and you want to get all the associated Color records, you can do:

@sector.colors

If you want to associate a @color with a @sector, then you do:

@sector.colors << @color

This, and more, is all covered thoroughly in the docs.

like image 65
jvillian Avatar answered Dec 13 '25 16:12

jvillian