Rails 4:schema.db显示"无法转储表"事件"因为对于nil遵循NoMethodError #undefined方法`[]':NilClass"

hue*_*nix 19 ruby-on-rails rails-migrations ruby-on-rails-4

我一直在研究一个带有sqlite(Rails开发环境的默认设置)的Rails 4.0应用程序,用于事件(黑客马拉松),它有一个父模型,Event,可以有很多Press_Blurbs.

首先,我运行了一些脚手架生成器,这些生成器创建了一些我看似没有问题的迁移:

class CreateEvents < ActiveRecord::Migration
  def change
    create_table :events do |t|
      t.string :city
      t.string :theme
      t.datetime :hackathon_start
      t.datetime :hackathon_end
      t.datetime :show_start
      t.datetime :show_end
      t.text :about
      t.string :hack_rsvp_url
      t.string :show_rsvp_url

      t.timestamps
    end
  end
end

class CreatePressBlurbs < ActiveRecord::Migration
  def change
    create_table :press_blurbs do |t|
      t.string :headline
      t.string :source_name
      t.string :source_url
      t.string :logo_uri

      t.timestamps
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

然后我为模型添加了一些关系:

class Event < ActiveRecord::Base
  has_many :press_blurbs
end

class PressBlurb < ActiveRecord::Base
  belongs_to :event
end
Run Code Online (Sandbox Code Playgroud)

...并添加/运行迁移以添加表引用:

class AddEventRefToPressBlurbs < ActiveRecord::Migration
  def change
    add_column :press_blurbs, :event, :reference
  end
end
Run Code Online (Sandbox Code Playgroud)

然而,当我查看schema.db时,这是我看到的而不是表定义:

# Could not dump table "events" because of following NoMethodError
#   undefined method `[]' for nil:NilClass

# Could not dump table "press_blurbs" because of following NoMethodError
#   undefined method `[]' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)

其他不相关的表在schema.rb中显示完全正常,但这些表没有.知道发生了什么事吗?

Jos*_*wis 20

我认为你上次的迁移是错误的.我会改为:

class AddEventRefToPressBlurbs < ActiveRecord::Migration
  def change
    add_reference :press_blurb, :event
  end
end
Run Code Online (Sandbox Code Playgroud)

不幸的是,您的数据库可能处于不稳定状态,因为它具有无效的列类型(即没有'引用'列类型,但sqlite无论如何都是这样做的).希望它只是一个开发数据库,​​所以你可以删除它并重新开始.

  • `bundle exec rake db:reset`通常是有效的,但是当你的schema.rb错误时,类似于`bundle exec rake db:drop db:create db:migrate`的工作效果更好. (8认同)