創(chuàng)建toy-app應(yīng)用:
cd ~/workspace
rails new toy_app
cd toy_app/
參照使用Heroku部署hello_app,修改Gemfile文件,然后執(zhí)行:
bundle install --without production #安裝gem
git init #把toy_app納入git中
git add -A
git commit -m "Initialize repository"
git remote add origin git@bitbucket.org:<username>/toy_app.git
git push -u origin --all
參照創(chuàng)建第一個(gè)應(yīng)用hello_app修改toy_app應(yīng)用中的app/controllers/application_controller.rb文件,定義動(dòng)作。
提交改動(dòng),再推送到 Heroku 中:
git commit -am "Add hello"
heroku create
git push heroku master
Users資源:創(chuàng)建用戶
接下來(lái),利用腳手架scaffold,生成Users資源:
rails generate scaffold User name:string email:string
rails db:migrate #遷移數(shù)據(jù)庫(kù)
執(zhí)行rails s命令后,在瀏覽器打開(kāi) http://localhost:3000/users 就可以看到,是一個(gè)可以創(chuàng)建用戶的界面了(好可惜,這里沒(méi)有截圖),并且可以創(chuàng)建、編輯、刪除用戶。
修改toy_app/config/routes.rb文件,改變跟路由:
Rails.application.routes.draw do
resources :users
root 'users#index'
end
Microposts資源:創(chuàng)建微博
同樣利用scaffold生成Microposts資源:
rails generate scaffold Micropost content:text user_id:integer
rails db:migrate
執(zhí)行rails s命令后,在瀏覽器打開(kāi) http://localhost:3000/microposts/new 就可以看到,是一個(gè)可以創(chuàng)建微博的界面了。試著輸入一些內(nèi)容吧。
在toy_app/app/models/micropost.rb中可以限制微博的長(zhǎng)度:
class Micropost < ApplicationRecord
validates :content, length: { maximum: 140 }
end
修改toy_app/app/models/user.rb文件,設(shè)置一個(gè)用戶可擁有多篇微博:
class User < ApplicationRecord
has_many :microposts
end
修改toy_app/app/models/micropost.rb,設(shè)置一篇微博屬于一個(gè)用戶:
class Micropost < ApplicationRecord
belongs_to :user
validates :content, length: { maximum: 140 }
end
修改toy_app/app/models/micropost.rb文件,添加驗(yàn)證微博內(nèi)容存在性的代碼:
class Micropost < ApplicationRecord
belongs_to :user
validates :content, length: { maximum: 140 },
presence: true
end
修改toy_app/app/models/user.rb,添加驗(yàn)證用戶名和郵件存在性的代碼:
class User < ApplicationRecord
has_many :microposts
validates :name, presence: true
validates :email, presence: true
end
部署:
git add -A
git commit -m "finished"
git push
heroku create
git push heroku
heroku run rails db:migrate #遷移生產(chǎn)數(shù)據(jù)庫(kù)
好了,今天的學(xué)習(xí)終于是在“碰到問(wèn)題to解決問(wèn)題”的過(guò)程中完成了,實(shí)踐出真理,動(dòng)動(dòng)腦筋,靈活學(xué)習(xí),任何困難都會(huì)迎刃而解的。