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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With