【问题标题】:db:migrate table not being createddb:未创建迁移表
【发布时间】:2013-07-03 20:12:17
【问题描述】:

我正在尝试创建一个包含 3 列 url、价格和时间戳的表...我尝试了“更改”和“向上”

class Shp < ActiveRecord::Base
  def change
    create_table :shps do |t|
      t.string :url
      t.float :price
      t.timestamps
    end
  end
end

运行 db:migrate 似乎什么都不做,就像我做的那样

ActiveRecord::Base.connection.column_names("shps")

我得到一个只有默认列的表格。

=> [#<ActiveRecord::ConnectionAdapters::SQLiteColumn:0x8fc8a34 @name="id", @sql_type="INTEGER", @null=false, @limit=nil, @precision=nil, @scale=nil, @type=:integer, @default=nil, @primary=nil, @coder=nil>, #<ActiveRecord::ConnectionAdapters::SQLiteColumn:0x8fc878c @name="created_at", @sql_type="datetime", @null=false, @limit=nil, @precision=nil, @scale=nil, @type=:datetime, @default=nil, @primary=nil, @coder=nil>, #<ActiveRecord::ConnectionAdapters::SQLiteColumn:0x8fc8444 @name="updated_at", @sql_type="datetime", @null=false, @limit=nil, @precision=nil, @scale=nil, @type=:datetime, @default=nil, @primary=nil, @coder=nil>]

【问题讨论】:

  • 你用“column_names”方法测试:shps是一个表的存在吗?也许您可以通过 Ruby 以外的其他工具(用于 PostGreSQL 的 PGAdmin3 等)进行检查

标签: ruby-on-rails activerecord rake


【解决方案1】:

迁移类应该继承自 ActiveRecord::Migration 而不是 ActiveRecord::Base。它们也应该放在正确的目录(db/migrate)中,并且它们的文件名应该包含适当的时间戳。

要在模型之间生成迁移,您应该在控制台中输入:

rails g model Shp url:string price:float

并运行迁移:

bundle exec rake db:migrate

顺便说一句,为了您自己的方便,请尝试使类名更具描述性。

【讨论】:

    【解决方案2】:

    这应该可行:

    app/models/shp.rb:

    class Shp < ActiveRecord::Base
      set_table_name "shps"
    end
    

    db/migrate/2013xxxxxxxxx_create_shps.rb:

    class CreateShps < ActiveRecord::Migration
      def change
        create_table(:shps) do |t|
          t.string :url
          t.float :price
          t.timestamps
        end
      end
    end
    

    HTH

    【讨论】:

    • 两个类会放在同一个文件中吗?
    • 当然不是,因为您使用的是 Ruby on Rails,我想您知道将它们放在哪里(为清楚起见,编辑了原始答案)。
    猜你喜欢
    • 2013-09-26
    • 2017-07-02
    • 2021-01-21
    • 1970-01-01
    • 2017-11-04
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    相关资源
    最近更新 更多