Migrations
Create CRUD operations using scaffold
rails generate scaffold Article title:string description:text
Above command generates following files
Running via Spring preloader in process 6362
invoke active_record
create db/migrate/20161116062714_create_articles.rb
create app/models/article.rb
invoke test_unit
create test/models/article_test.rb
create test/fixtures/articles.yml
invoke resource_route
route resources :articles
invoke scaffold_controller
create app/controllers/articles_controller.rb
invoke erb
create app/views/articles
create app/views/articles/index.html.erb
create app/views/articles/edit.html.erb
create app/views/articles/show.html.erb
create app/views/articles/new.html.erb
create app/views/articles/_form.html.erb
invoke test_unit
create test/controllers/articles_controller_test.rb
invoke helper
create app/helpers/articles_helper.rb
invoke test_unit
invoke jbuilder
create app/views/articles/index.json.jbuilder
create app/views/articles/show.json.jbuilder
create app/views/articles/_article.json.jbuilder
invoke assets
invoke coffee
create app/assets/javascripts/articles.coffee
invoke scss
create app/assets/stylesheets/articles.scss
invoke scss
create app/assets/stylesheets/scaffolds.scss
rake db:migrate
delete existing scaffold
rails destroy scaffold Article
**Add foreign key when using scaffold
rails generate scaffold Comment description:text user:references
Writing migrations
rails generate migration create_articles
following migration file will be created automatically
db/migrate/20161116072421_create_articles.rb
class CreateArticles < ActiveRecord::Migration[5.0]
def change
create_table :articles do |t|
end
end
end
Add column 'title' to a Article table
class CreateArticles < ActiveRecord::Migration[5.0]
def change
create_table :articles do |t|
t.string :title
end
end
end
run rake db:migrate
Notice changes in file db/schema.rb
ActiveRecord::Schema.define(version: 20161116072421) do
create_table "articles", force: :cascade do |t|
t.string "title"
end
end
Add new column to existing table
rails generate migration add_description_to_articles
New migration file will created automatically
db/migrate/20161116074259_add_description_to_articles.rb
class AddDescriptionToArticles < ActiveRecord::Migration[5.0]
def change
end
end
Modify file like this
class AddDescriptionToArticles < ActiveRecord::Migration[5.0]
def change
add_column :articles, :description, :text
add_column :articles, :created_at, :datetime
add_column :articles, :updated_at, :datetime
end
end
run rake db:migrate
Notice changes in file db/schema.rb
ActiveRecord::Schema.define(version: 20161116074259) do
create_table "articles", force: :cascade do |t|
t.string "title"
t.text "description"
t.datetime "created_at"
t.datetime "updated_at"
end
end
rake db:rollback