如何在将 "accepts_nested_attributes_for" 添加到模型后更新架构

how to update schema after adding "accepts_nested_attributes_for" to a model

这是我的模型

class Lineup < ApplicationRecord
  has_many :artists
  accepts_nested_attributes_for :artists
  belongs_to :event
end

class Artist < ApplicationRecord
  has_many :events, :through => :lineups
  has_many :lineups
end

当 运行在控制台中设置此

Lineup.new(artists_attributes: [{artist_id: 1}, {artist_id: 2}])

错误是 ActiveModel::UnknownAttributeError: unknown attribute 'artists_attributes' for Lineup. 显然,我不能只是将类似的东西放入模型中并期望任何更改仅来自于它。我需要为此 运行 迁移吗?如果是这样,它需要包含什么?

架构:

  create_table "artists", force: :cascade do |t|
    t.string   "name"
    t.text     "bio"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer  "lineup_id"
    t.integer  "event_id"
  end

  add_index "artists", ["event_id"], name: "index_artists_on_event_id", using: :btree
  add_index "artists", ["lineup_id"], name: "index_artists_on_lineup_id", using: :btree

create_table "lineups", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer  "artist_id"
    t.integer  "event_id"
  end

  add_index "lineups", ["artist_id"], name: "index_lineups_on_artist_id", using: :btree
  add_index "lineups", ["event_id"], name: "index_lineups_on_event_id", using: :btree

我会这样设置

架构

table Lineup
  ...

table Artist
  ...

table LineupArtists
  lineup_id: Integer
  artist_id: Integer

型号

class Artist < ApplicationRecord
  has_many :lineup_artists, dependent: :destroy
  has_many :lineups, through: :lineup_artists
end

class LineupArtist < ApplicationRecord
   belongs_to :lineup
   belongs_to :artist

   accepts_nested_attributes_for :lineup
end 

class Lineup < ApplicationRecord
  has_many :lineup_artists, inverse_of: :lineup, dependent: :destroy
  has_many :artists, through: lineup_artists

  accepts_nested_attributes_for :lineup_artists
end

你目前拥有它的方式(Artists 有一个 lineup_id 和 Lineups 有一个 artist_id)每个模型只能有另一个(即。 Artist 可以有一个阵容,反之亦然)。联接 table 提供了建立多对多关系的能力。

设置嵌套属性对于多对多有点棘手,但我相信我 posted 应该涵盖它。如果没有从这个 post (https://robots.thoughtbot.com/accepts-nested-attributes-for-with-has-many-through) 中得到一些更奇怪的位。希望这有帮助。

尝试替换行:

has_many :artists

有了这个:

has_many :artists, foreign_key: "lineup_id"