2015年3月9日 星期一

Ruby on Rails 環境建置、基本網站建立

照理來說應該是要在本機端操作,但系統是windows,在windows平台底下使用ruby會有些問題,一些熟悉的指令無法直接在windows的終端機使用,原本是使用VM(虛擬機器)裝ubuntu,但大家的環境都有問題,要一個一個除錯要花非常多時間,就決定使用網路版的開發環境nitrous.io,結果又有問題,nitrous進不去!一直卡在starting的畫面,卡了10多分鐘,後來改使用另一個線上服務Cloud9功能跟nitrous差不多,才終於順利開始課程。



ruby基本操作
ruby -v 查看ruby版本
rails -v 查看rails版本
gem install rails -v 4.2.0 安裝新版本的rails
rails new bookstore 建立一個bookstore專案
bundle install 安裝套件

一些注意事項
  1. convenstion over configutation(CoC)按照慣例來寫
  2. don't repeat yourself(DRY)不要重複的程式碼
  3. create,read,update,delete (CRUD)新增、修改、更新、刪除
  4. Model 資料、資料庫, View 跟畫面有關, Controller(MVC)
t.timestamps null: false會自動新增created_at新增日期和updated_at更新日期

HTPP Request
Get
打網址
Post
表單送出資料,一整包一起送

常用指令
ls 列出當前目錄下的所有檔案,資料夾
cd
touch
sudo
rm, mv, cp
rails, bundle, rake, git

開始
step1 建立資料表的架構:
rails generate scaffold book title:string content:text price:integer page:integer publish_date:date is_online:boolean

step2 依據架構實際建立一個資料表:
rake db:migrate

step3
使用本機端
rails server
在線上環境中的終端機改使用
rails server -p $PORT -b $IP

step4
使用本機端
開瀏覽器
http://localhost:3000/books

在線上環境中
使用preview,然後在網址後加上books

與mvc架構對應
Model (app/models/book.rb)
View (app/views/books/index.html.erb)
Controller(app/controllers/books_controller.rb)
Router(config/routes.rb)

rake routes
哪一個網址要做哪一種動作

繼續實作
再新增一個資料表架構
rails g scaffold post title content:text user_id:integer
建立資料表
rake db:migrate

rails c 進入ruby的後台(irb)
可直接在後台打指令

u1=User.find_by(id:1)
pl=Post.find_by(id:1)

若想要將Users、Posts 2個資料表有關連
在user.rb中打
has_many :posts  代表一個使用者可以有很多posts
在post.rb中打
belongs_to :user   代表post屬於user

存檔後在終端機(rails c)打reload!,將檔案重新載入
之後再重新將post的第一筆紀錄存到p1中(Post.find_by(id:1))
p1.user能將users中與posts的user_id相對應的資料找出
接下來使用p1.user.name就可以找出post_id為1的user的name

在rails c中也可以直接修改資料表中的值
一樣先將某一筆資料存進p1中
指定修改哪一個欄位,後面接=與要修改的值
再來p1.save將修改的值存進資料庫中

驗證
以往要寫欄位驗證要透過javascript
先指定要在哪一個
validates:title,presence:true
validates:name,length:{minimum:5}