###### tags: `Ruby` # rails 純手工打造 rails routes(終端機指令) 可看見所有路徑 1. 在routes.rb裡加上resource :candidate(範例) 2. 找不到controller 3. 到controllers裡面新增 candidates_controller.rb 4. 在檔案中命名class並繼承至ApplicationController(慣例CandidatesController要加s) 5. 找不到view 6.  **慣例:CandiatesController對應到views裡面的candidates資料夾,所以要在views裡建立此資料夾** 8. 在controller裡def index 並且在candidates裡新增index.html.erb使之對應 9. 使用終端機建立model下指令後創造出Candidate的model以及migration檔 10. 在終端機下 rails db:migrate 將資料寫入資料表 # 製作表單 1. 找路徑 2. 沒有new這個action,做給他 3.  4. 沒有view,做給他 5.  6. 用POST方法做表單,post對應到create action 7. 製作表單 8. 畫面中按下go!之後顯示找不到 create這個action的頁面 9. 做給他! 10. 表單需要authenticity token否則可能遭有心人士偷傳資料近來 11. 加上authenticity token 12. formhelper寫法,可將Candidate.new寫在controller裡的new方法並將其指定給@candidate這個實體變數供這裡使用 13.  畫面呈現 14.  設定create 將資料寫進資料庫 15. 出錯! 原因:資料未經驗證系統檔下,因為雖然表單已設定好但使用者仍可以在頁面上手動增加欄位。 16. 做資料驗證,隨後再加上提醒(flash)來提醒使用者提交成功。 17. 填入失敗時使用reder :new來借new的頁面來重新渲染而不是再到一個新的頁面,並且表單會在抓一次@candidate的資料再填入這樣就不用再填一次,也因為前面刻意將new、create的變數設為@candidate所以在這個情況可以這樣操作。 # 讓candidate資料顯示在index頁面 1. 設定@candidates撈出所有資料 2. 在index頁面建立表格,想將name設為超連結並將politics放在那裏面但該導向哪裡? 3.  找到路徑,並且得知會指向show方法 4.  換上便可以使知道每個id的頁面 5. 用link_to取代 a 6. "/candidates/new"可以使用new_candidate(後面可以加東西)來替代 7. 像這樣子 8. **這樣子做有什麼好處呢??** 1.打錯字時會出錯 2.只要在candidate.rb裡下指令就可以改變網址的內容 9.  更改後的樣子最後記得將id參數給路徑 10. **建立show頁面**  先建立action 且設變數 11. 建立show的views並判斷id存不存在資料庫。 12.
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up