rails new <appname>
This rails command takes as an argument the name of the project. It will create a subdirectory called app in the current working directory. The standard database preconfigured is SQLite. If you wish to configure other databases such as mysql, oracle, postgresql, sqlite2, sqlite3, pass the -d or –database=option to the command above.
rake db:create:all (this will create test and production databases)
You can get rails to create a new database for you by running the rails command above. If you are using SQLite, the database will be automatically created for you.
Step 3 (Optional)
This will allow you to look into the tables and records created for your application.
Step 4 (Optional)
This will check if your application is connected to a database. You will see an error below if you did not configure the root’s password properly.
Access denied for user ‘root’@’localhost’ (using password: NO)
rails generate model ModelName title:string body:text published_at:datetime
This command will create a model for the database. The model names in Rails corresponded to database table names. Article (model, camel-cased singular) => articles (table, lower-cased plural). Rails has a complex pluralization rules coded into it. So Person will create a table named people. You may pass in –skip -migration if you do not want to create a migration file. This command will create 4 files.
If you are not planning to create tables manually through SQL, you can work with the migration file instead. After editing the migration file, run the rails command above.
Step 7 (Optional)
If you want to roll back the migration for any reason, run the rails command above. Due to the change instance method, it is easy for us to migrate-rollback database configurations.
rails generate controller articles
This will create six files.
app/controllers/articles_controller.rb – handle requests and responses for the model Article
test/controllers/articles_controller_test.rb – functional tests for articles controller
app/helpers/articles_helper.rb – add utility methods used in views
test/helpers/articles_helper_test.rb – all helper tests for helper class
app/assets/stylesheets/articles.css.scss – CSS specific to articles views
rails generate migration add_excerpt_and_location_to_articles excerpt:string location:string
If you wish to add more fields, you should do using migrations. Run the rails command above. The migration file appear like the code below.
class AddExcerptAndLocationToArticles < ActiveRecord::Migration def change #add_column method #first argument is table name (articles) #second argument is field name #third argument is field type add_column :articles, :excerpt, :string add_column :article, :location, :string end end #run rake db:migrate
The rules for data integrity are the responsibility of the model (app/models/article.rb)
class Article < ActiveRecord::Base validates_presence_of :title, :body end