Getting
Started with Rails
用Ruby on Rails純手工打造一個具從屬關係的[討論區]
在上一個範例中已經可以用純手工成功的完成簡易的CRUD應用程式,接下來要透過打造一個複雜一點的應用程式[討論區],來練習具有從屬關係的資料結構,也順便練一練CRUD,一定要透過不斷練習讓CRUD變得很自然。
討論區的結構中有許多Po文(Post),每個Po文會有許多評論(Comment),這樣的從屬關係非常適合當成範例來說明,所以我們的資料結構如下圖,Comment透過post_id與post做關聯。
1.     has_many與belongs_to的convention
上面這樣的結構我們可以說一個post可以具有has many的comment關係,而comment與post有著belongs to的關係。
| 
l         
  has_one 
l         
  has_many 
l         
  belongs_to 
l         
  has_many :through | 
好了,說明完我們的目標結構後,接下來就可以實作了。
1.     
建立一個專案
| 
$rails new sample042 
$cd sample042 | 
2.     
建立一個名為post的model,其中包含name, title與content三個欄位
| 
$rails g model post name:string title:sting content:text 
$rake db:migrate | 
完成後可以在 sample042/db/migrate/20131101062711_create_posts.rb看到:
3.     
建立一個名為posts的controller
| 
$rails g controller posts | 
4.     
修改/config/routes.rb
| 
Sample042::Application.routes.draw do 
resources :posts | 
2.     建立comment與post的關聯
Post與comment這樣的透過post_id連結的關聯性,需要透過references的作法關聯起來。
5.     
建立一個名為comment的model,其中包含cmment與body兩個欄位,以及與post的關聯
| 
$rails g model comment commenter:string body:text post:references 
$rake db:migrate | 
透過post:references所建立的關聯就是本文一開始指的post_id,完成後可以在 sample042/db/migrate/ 20131101064406_create_comments.rb看到:
6.     
建立一個名為comment的controller
| 
$rails g controller comments | 
3.     雙層resources => Nested resources
7. 修改/config/routes.rb
7. 修改/config/routes.rb
| 
Sample042::Application.routes.draw do 
resources :posts do 
 
  resources :comments 
end | 
接下來就要逐一修改CRUD結構。
8.     
修改 /sample042/app/controllers/posts_controller.rb
9.     
修改 /sample042/app/controllers/comments_controller.rb
10.  修改 /sample042/app/models/post.rb 
11.  修改 /sample042/app/models/comment.rb 
12.  修改 /sample042/app/views/posts/index.html.erb
13.  修改 /sample042/app/views/posts/show.html.erb
14.  修改 /sample042/app/views/posts/new.html.erb
15.  修改 /sample042/app/views/posts/edit.html.erb
16.  修改 /sample042/app/views/comments/index.html.erb
(不會用到)
17.  修改 /sample042/app/views/comments /show.html.erb
18.  修改 /sample042/app/views/comments /new.html.erb
19.  修改 /sample042/app/views/comments /edit.html.erb
20.  做到這邊,我們要來驗收一下成果,透過powder來開瀏覽器驗收吧。
| 
$cd ~/projects/sample042 
$powder link 
$powder open | 
21.  完成CRUD功能囉,來驗收一下吧,應該可以看到這些頁面。
在瀏覽器上打上http://sample042.dev/posts/

Show出單筆post
新增一筆post
刪除post
Show出單筆post以及該post底下的comments
新增commnet
編輯comment
刪除comment






















留言
張貼留言