【问题标题】:Join Table issue with rails 6使用rails 6加入表问题
【发布时间】:2020-02-14 12:11:26
【问题描述】:

我有一个颜色模型:

class Color < ApplicationRecord
  belongs_to :sector

扇形模型:

class Sector < ApplicationRecord
  has_many :colors

我创建了一个连接表,例如:

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 

现在我想获取属于特定扇区的所有颜色。我试过了:

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

但它返回一个错误→uninitialized constant Color::Sectors

【问题讨论】:

  • ColorScheme 是什么? colore_idhas_many :color(应该是复数)中有一个错字。您是否在运行迁移后更新了模型?您是否为连接表创建了模型?为什么要在一对多关系中使用连接表?
  • 我修正了我不是连接表模型的拼写错误,我应该这样做吗?我尝试获取属于特定部门的所有颜色,我认为加入是要走的路
  • 我认为没有它你也没问题。看看你的关系,它们是“颠倒的”,一种是复数形式,而应该是单数形式(颜色),另一种是单数形式,应该是复数形式(部门)。 Color.where(sector_id: sector.id) 可能会起作用。
  • 试试Color.joins(:sector)

标签: ruby-on-rails ruby join activerecord


【解决方案1】:

如果您需要多对多关系,请使用has_and_belongs_to_many 关联

【讨论】:

    【解决方案2】:

    如果您有 Color 模型,例如:

    # == 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
    

    还有一个Sector 模型,例如:

    # == 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
    

    然后你创建你的ColorSector 模型:

    # == 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
    

    当您有一个@color 并且想要获取所有关联的Sector 记录时,您可以这样做:

    @color.sectors
    

    当你有一个@sector 并且你想获取所有关联的Color 记录时,你可以这样做:

    @sector.colors
    

    如果您想将@color@sector 关联,那么您可以:

    @sector.colors << @color
    

    docs 彻底涵盖了这一点以及更多内容。

    【讨论】:

    • 我需要创建ColorSector 模型吗,我认为没有它我可以做到
    • 为什么没有ColorSector 模型? Rails 完全是关于约定的,这是进行 m:m 关联的传统方式。 (我猜你可以做一个 HABTM,但我从来没有使用过。)
    猜你喜欢
    • 1970-01-01
    • 2019-09-14
    • 2021-03-31
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多