如何添加到设计模型?

问题描述:

我通过命令rails generate devise Users创建用户模型。如何添加到设计模型?

我想我的Users模型保持不变但我想添加更多的列,但我不知道如何和我现在仍然有点困惑。我对Ruby on Rails很新颖。我不确定在做出这些更改之后,我应该运行什么命令。我认为它是rake db:migrate为了更新数据库。

我希望能够加入

name - string 
address - string 
username - string .. 

根据这个实例文档中,

class AddDetailsToProducts < ActiveRecord::Migration 
    def change 
    add_column :products, :part_number, :string  
    add_column :products, :price, :decimal 
    end 
end 

里面的change方法,添加列part_number(串)和price(十进制)到products

请问

文件:20141011161019_devise_create_users.rb

class DeviseCreateUsers < ActiveRecord::Migration 
    def change 
    create_table(:users) do |t| 
     ## Database authenticatable 
     t.string :email,    null: false, default: "" 
     t.string :encrypted_password, null: false, default: "" 

     ## Recoverable 
     t.string :reset_password_token 
     t.datetime :reset_password_sent_at 

     ## Rememberable 
     t.datetime :remember_created_at 

     ## Trackable 
     t.integer :sign_in_count, default: 0, null: false 
     t.datetime :current_sign_in_at 
     t.datetime :last_sign_in_at 
     t.inet  :current_sign_in_ip 
     t.inet  :last_sign_in_ip 

     ## Confirmable 
     # t.string :confirmation_token 
     # t.datetime :confirmed_at 
     # t.datetime :confirmation_sent_at 
     # t.string :unconfirmed_email # Only if using reconfirmable 

     ## Lockable 
     # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts 
     # t.string :unlock_token # Only if unlock strategy is :email or :both 
     # t.datetime :locked_at 


     t.timestamps 
    end 

    add_index :users, :email,    unique: true 
    add_index :users, :reset_password_token, unique: true 
    # add_index :users, :confirmation_token, unique: true 
    # add_index :users, :unlock_token,   unique: true 
    end 
end 

不要改变现有的移民。您希望使用命令rails generate migration MigrationName创建新的迁移,然后按照Active Record Migrations Rails指南进行操作,该指南提供了大量有关如何添加数据库列的示例。

+0

行'add_column:products,:part_number,:string'是否将列part_number(字符串)添加到产品表中? – Liondancer 2014-10-12 06:58:40

+1

是的。第一个参数是表名,第二个是字段名,第三个是类型。 – 2014-10-12 07:00:17

首先,运行rake db:migrate。这将运行devise在数据库中准备的迁移。

之后,只需添加更多字段到您的模型,就像您从未安装过设计一样。第一步是生成一个新的迁移。在命令行中运行以下命令:

bin/rails generate migration AddNameAddressUsernameToUsers name:string address:string username:string

这将创建一个新的迁移文件。然后,您应该再次在rake db:migrate的数据库上运行该迁移文件。之后,您应该能够在控制器和视图中引用这些新模型字段。

虽然您可以在一次迁移中完成所有操作,但通常情况下最好保持迁移小而离散。如果出现任何问题,这可以更轻松地解决问题。