【问题标题】:adding a new table using rails migration..?使用 Rails 迁移添加新表..?
【发布时间】:2015-04-21 09:40:19
【问题描述】:

我想使用 Rails 迁移添加新表:

**table_name** users_location_track
**columns** id (primary key, auto increment serial),
            user_id (reference to users), location_info (string), 
            creation_time(time-stamp)

请建议程序和代码我是 Rails 新手?

【问题讨论】:

  • 这是非常基本的东西,所以我建议从一些教程/指南开始,例如:guides.rubyonrails.org
  • 嘿@MarekLipka 如何在创建表时添加 ref 类型

标签: rails-migrations ruby-1.8.7


【解决方案1】:

在 Rails 中,我们不会像您要求的那样做。您需要编写如下命令:

 rails generate migration CreateUserLocationTrack user_id:integer location_info:string 

你不需要creation_time,因为created_at是默认创建的。

更多信息请关注rails guide

【讨论】:

  • 嘿@Manish,我探索了这么多,但我想将 user_id 设为 ref 类型。
  • @piyushmandovra,使用 add_foreign_key :users_location_track, :users 并查看迁移指南了解更多信息。
  • 所以我应该添加另一个迁移还是在同一个迁移中我可以添加参考
  • @piyushmandovra,您可以在运行之前编辑迁移rake db:migrate
【解决方案2】:

感谢您的批评。 我终于得到了答案:

这里是未来任何想要的人的解决方案。

首先进入项目目录,然后运行以下命令

rails generate migration add_user_lat_long

然后会生成一个迁移文件,然后您可以按照以下样式进行编辑:

class AddUserLatLong < ActiveRecord::Migration
  def self.up
    create_table :users_location_track do |t|
      t.string :location_info
      t.references :user

      t.timestamps

end
    add_index :users_location_track, :user_id, :name =>'index_user_lat_longs_on_user_id'
  end

  def self.down
        drop_table :users_location_track
  end
end

【讨论】:

    猜你喜欢
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多