Rails Routing part1

Posted by Anthony Chao on 2019-10-02

今天的主要內容都來自這裏,在介紹 Rails 的 routes 寫法

土炮寫法

routes 在 rails 裡面非常重要,就算你的程式寫得再好忘記加上路徑就也沒人能找到你的頁面

最土砲的寫法,就是使用 get 跟 to 來引導到正確的頁面

1
2
#routes.rb
get '/patients/:id', to: 'patients#show'

或是可以把 controller 跟 action 寫的更直白

1
2
#routes.rb
get '/patients/:id', action: :show, controller: 'patients'

上面這個例子會引導到 patients controller 裡面的 show action,然後 id 會去抓 params[:id] 內容

慣例寫法

不過 routes 最常用的還是使用慣例的 resources 方法,他會幫你產生 7 條常用的路徑如下範例

1
2
#routes.rb
resources :photos

當你的這個 controller 並不是複數的時候,也已經幫我們準備好這個慣例了,這種情況下就是少了 index 的頁面

1
2
#routes.rb
resource :geocoder

設計慣例 routes

我們還可以在 routes 上面加上一些設計,比方說加上 namespace:

1
2
3
namespace :admin do
resources :articles
end

除了路徑需要改之外,你的 controller 也要使用 Admin::ArticlesController 來做設定喔

那如果我不想改 controller 只想改路徑勒?

1
2
3
4
5
scope '/admin' do
resources :articles, :comments
end
# 或者
resources :articles, path: '/admin/articles'

如此一來只有路徑會變,controller 不變

那如果我只想改 controller 不想改路徑呢?

1
2
3
4
5
scope module: 'admin' do
resources :articles, :comments
end
# 或者
resources :articles, path: '/admin/articles'

如此一般,你的路徑還是不變,但 controller 已經變成 Admin::ArticlesController 囉

今天的內容就到這裡囉~我們明天見!

參考資料:

Rails Guide





prevent_hack