iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 13
0
Modern Web

Ruby on Rails面試題挑戰系列 第 13

Ruby on Rails面試題挑戰 Day13 - 不要使用“resources”的情況下,定義一條route給create action

經過好幾天Ruby面試題的洗禮,我們就正式開始看看Rails相關的面試題,今天先來個牛刀小試

Define a route for a create action without using “resources”
不要使用“resources”的情況下,定義一條route給create action


當使用者輸入網址,第一個會遇到的就是Rails網站的Routes,也就是路徑對照表。路徑上會記載輸入的網址會對應到的Controller及Action,如果沒有,就會顯示找不到頁面(404)給使用者。

一般我們在Rails中會傾向使用resources來建立路徑,舉下面例子為例

Rails.application.routes.draw do
  resources :user
end

會幫你產生8條路徑,7個action,可以在終端機輸入rails routes來查看現有路徑

rails routes
   Prefix Verb   URI Pattern               Controller#Action
    users GET    /users(.:format)          users#index
          POST   /users(.:format)          users#create
 new_user GET    /users/new(.:format)      users#new
edit_user GET    /users/:id/edit(.:format) users#edit
     user GET    /users/:id(.:format)      users#show
          PATCH  /users/:id(.:format)      users#update
          PUT    /users/:id(.:format)      users#update
          DELETE /users/:id(.:format)      users#destroy

也就是所謂的CRUD,C指的是Create(新增),R是Read(檢視),UUpdate(修改),D是Destroy(刪除),若只想要有index action,可以在resources後面補上only: [:index],就只會創立第一條對應到users#index(Controller#action)的路徑。

Rails.application.routes.draw do
  resources :user, only: [:index]
end

如果不用resoures的方式,可以用下面這種寫法。

Rails.application.routes.draw do
  get '/users', to: "users#index"
end

意思是用get方法打到/users這個網址時,Rails會去幫你找users_controller的index這個action。

回到題目本身,若要創立一條create路徑,可以用下面這種寫法

Rails.application.routes.draw do
  post '/users', to: "users#create"
end

要注意的是Create這個action要用post方法打,後面用to:的方式來指定要的controller與action。

你可以這樣回答:

不使用resources寫法的話,要使用以下這種寫法來創立create action。

Rails.application.routes.draw do
  post '/users', to: "users#create"
end

參考資料

為你自己學 Ruby on Rails - Routes


上一篇
Ruby on Rails面試題挑戰 Day12 - 在Ruby中的self是什麼?我們什麼時候會使用self?
下一篇
Ruby on Rails面試題挑戰 Day14 - 什麼是MVC?
系列文
Ruby on Rails面試題挑戰30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言