Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to add attributes to User Model in Ruby on Rails

my User Model looks like:

    class CreateUsers < ActiveRecord::Migration
       def self.up
         create_table :users do |t|
         t.string :name
         t.string :email

         t.timestamps
       end
    end

      def self.down
        drop_table :users
        end
      end

If I wanted add one more :attribute, is it best to create another migration file for adding a new column (see another Stackoverflow thread) or can I just manually add t.string :name_of_new_attribute and then rake db:migrate?

Thanks!

like image 823
Elias7 Avatar asked Apr 16 '12 01:04

Elias7


People also ask

Which of the following options can be used to add attributes in a model?

alter table r add A D; where r is the name of an existing relation, A is the name of the attribute to be added, and D is the type of the added attribute.

What's the purpose of Active Record?

Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.

What is Active Record Rails?

Rails Active Record is the Object/Relational Mapping (ORM) layer supplied with Rails. It closely follows the standard ORM model, which is as follows − tables map to classes, rows map to objects and. columns map to object attributes.

What is Rails Activemodel?

Active Model is a library containing various modules used in developing classes that need some features present on Active Record.


1 Answers

The proper way is to create a new migration. In the main rails project folder, run

rails generate migration AddDetailsToUser address:string age:integer etc...

and then run rake db:migrate

An alternative to this is to edit the original migration file, reset/destroy the database and re-run all migrations.

like image 176
Norto23 Avatar answered Oct 06 '22 00:10

Norto23