【问题标题】:Rails5 add references to create one to manyRails5 添加引用创建一对多
【发布时间】:2016-07-27 02:44:08
【问题描述】:

我创建了两个模型调用Restaurantmenu,以及Restaurant has_many Menu。 我通过键入

创建菜单
rails g model Menu name restaurant:references

但我发现我无法按Menu.create(name: "test1") 类型创建菜单

m1 = Menu.create(name: "test1")
   (0.2ms)  BEGIN
   (0.2ms)  ROLLBACK
 => #<Menu id: nil, name: "test1", restaurant_id: nil, created_at: nil, updated_at: nil>

然后我检查了migrationschema,在Rails5迁移中references变成了这个

#Menu migration
...
t.references :restaurant, foreign_key: true

我认为在 Rails4 中,它会像

t.references :restaurant, index: true

这就是我无法创建meun的原因吗?

更新

这里是迁移文件

class CreateMenus < ActiveRecord::Migration[5.0]
  def change
    create_table :menus do |t|
      t.string :name
      t.references :restaurant, foreign_key: true

      t.timestamps
    end
  end
end

【问题讨论】:

  • 您运行迁移了吗?
  • 你能发布你的迁移文件吗?
  • 我确实运行了迁移并且我已经更新了迁移文件。

标签: ruby-on-rails ruby migration ruby-on-rails-5


【解决方案1】:

您无法创建菜单,因为您的迁移包含对 restaurant_id 的外键约束,这意味着如果没有餐厅,则无法创建菜单(类似地,如果存在关联的菜单,则无法销毁餐厅)。如果这是您的意图,您需要在创建菜单时提供有效的 restaurant_id 或通过 restaurant 上的关联创建它

@restaurant.menus.create(name: 'test1')

如果您不需要外键约束,请修改迁移并删除:foreign_key 选项。如果这样做,请将 :index 选项设置为 true。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 2021-02-27
    相关资源
    最近更新 更多