将“accepts_nested_attributes_for”添加到模型后如何更新架构

时间:2016-03-16 21:14:01

标签: ruby-on-rails nested-attributes

这是我的模特

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

2 个答案:

答案 0 :(得分:1)

我会像这样设置

模式

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可以有一个阵容反之亦然)。连接表提供了多对多关系的能力。

设置嵌套属性对于多对多来说有点棘手,但我相信我发布的内容应该涵盖它。如果没有从这篇文章中获得一些更奇怪的位(https://robots.thoughtbot.com/accepts-nested-attributes-for-with-has-many-through)。希望这会有所帮助。

答案 1 :(得分:0)

尝试替换行:

has_many :artists

有了这个:

has_many :artists, foreign_key: "lineup_id"