我想在两个模型 Bar 和 Foo 之间创建一个树结构。
酒吧有很多 Foos
Bar
/ | \
Foo Foo Foo
¦
Bar
/ | \
Foo Foo Foo
Bar 可以选择属于 Foo。
酒吧有许多 Foos,无穷无尽……
我配置了这样的东西,但它似乎没有正确播种。
即使我注释掉我拥有的任何验证,我也会收到以下错误:
ActiveRecord::RecordInvalid: Validation failed: Foos bar must exist
我不明白为什么。
class Bar < ApplicationRecord
has_many :foos, inverse_of: :bar
accepts_nested_attributes_for :foos
end
class Foo < ApplicationRecord
belongs_to :bar, inverse_of: :foos
accepts_nested_attributes_for :bar
end
class CreateFoos < ActiveRecord::Migration[6.1]
def change
create_table :foos do |t|
t.text :description, null: false
t.timestamps
end
end
end
class CreateBars < ActiveRecord::Migration[6.1]
def change
create_table :bars do |t|
t.text :description
t.references :foo,
foreign_key: true,
null: true,
on_delete: :cascade,
on_update: :cascade
t.timestamps
end
end
end
class AddBarIdToFoosTable < ActiveRecord::Migration[6.1]
def change
add_reference :foos,
:bar,
foreign_key: true,
null: false,
on_delete: :cascade,
on_update: :cascade
end
end
Bar.create!([
{
description: 'Lorem ipsum...',
foos_attributes: [
{
description: 'Lorem ipsum...',
bar_attributes: {
description: 'Lorem ipsum...',
foos_attributes: [
{
description: 'Lorem ipsum...',
bar_attributes: {
description: 'Lorem ipsum...',
foos_attributes: [
{
description: 'Lorem ipsum...'
},
{
description: 'Lorem ipsum...'
},
{
description: 'Lorem ipsum...'
},
{
description: 'Lorem ipsum...'
}
]
}
}
]
}
}
]
}
])