爲了清晰起見,我第二次重讀railstutorial。我試圖理解由rails提供的RESTful resources,它列出了各種HTTP請求和相應的控制器操作:index,show,new,create,edit,update,destroy。Rails RESTful控制器動作創建用戶
我從來沒有真正理解軌道控制器是如何工作的,我想澄清它。如果我製作了users_controller.rb
並且想要創建新用戶,那麼就是。我不在乎重定向,flash消息和其他flair。我只想創建新用戶並將其保存在我的數據庫中。我想做User.create(name: "Iggy1", email: "[email protected]")
。假設我進行了遷移,並且在數據庫模式上有name
(字符串)和email
(字符串)。
user_controller.rb創建用戶所需的最少代碼行是什麼?
我問這個問題的原因直到現在,我仍然不能100%確定哪個代碼行實際執行期望的操作。軌道是否足夠智能以識別這些特定關鍵字index
,new
,create
,destroy
, show
,edit
和update
,或者它們是否是任意的?如果rails足夠聰明地檢測這七個關鍵字,那麼只需列出方法(def destroy; #<no code>; end
),是否可以自動訪問DELETE用戶方法,或者我不得不說def destroy; User.find(params[:id]).destroy; end
使用DELETE用戶方法?在users_controller.rb
上,我最終從railstutorial中得到了這個精心製作的代碼。
...
def create
@user = User.new(user_params)
if @user.save
@user.send_activation_email
flash[:info] = "Please check your email to activate your account."
redirect_to root_url
else
render 'new'
end
end
...
Users_controller上只有def create
就足以讓rails創建用戶嗎?
def create
end
或者我至少需要有User.new
或更多代碼才能創建新用戶?
太謝謝你了,@toomanyrichies。這是我需要知道的。其他回答者巧合地提到了路由。有了這2個信息,我已經瞭解到關於資源的大量信息 – Iggy