Ruby on rails rails 6的联接表问题
我有一个彩色模型:Ruby on rails rails 6的联接表问题,ruby-on-rails,ruby,join,activerecord,Ruby On Rails,Ruby,Join,Activerecord,我有一个彩色模型: class Color < ApplicationRecord belongs_to :sector 但它返回了一个错误→ 未初始化的常量颜色::扇区如果您的颜色型号如下: # == Schema Information # # Table name: colors # # id :integer not null, primary key # created_at :datetime not null
class Color < ApplicationRecord
belongs_to :sector
但它返回了一个错误→ <代码>未初始化的常量颜色::扇区如果您的
颜色
型号如下:
# == 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
# == 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
然后创建ColorSector
模型,如下所示:
# == 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
# == 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
当您有一个@扇区
并且希望获得所有相关的颜色
记录时,您可以执行以下操作:
@sector.colors
如果要将@颜色
与@扇区
关联,请执行以下操作:
@sector.colors << @color
@sector.colors如果需要多对多关系,请使用关联什么是ColorScheme
?colore\u id
中有一个输入错误,有许多:color
(应该是复数)。运行迁移后是否更新了模型?您是否为联接表创建了模型?为什么要在一对多关系中使用联接表?我修复了输入错误,我不知道联接表的模型,应该吗?我试着找出属于某个特定领域的所有颜色,我认为加入是让我觉得没有它你就没事了。看看你的关系,它们是“颠倒的”,一个是复数,而它应该是单数(颜色),另一个是单数,当它应该是复数(扇形)Color.where(sector\u id:sector.id)
可能起作用。尝试Color.joins(:sector)
我需要创建colorsecast
模型吗,我想我可以不用它为什么不创建colorsecast
模型?Rails都是关于约定的,这是进行m:m关联的常规方式。(我想,你可以做一个HABTM,但我从来没有用过。)
@color.sectors
@sector.colors
@sector.colors << @color