Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails rails 6的联接表问题_Ruby On Rails_Ruby_Join_Activerecord - Fatal编程技术网

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