我正在學習「Ruby方式」並獲得樂趣,但是,我有這個塊按預期工作,但我知道它可能會更好。有人能告訴我使用unless
的正確方法嗎?這在UsersController中。使用除非運算符
def destroy
User.find(params[:id]).destroy unless current_user.admin?
flash[:success] = "User destroyed."
redirect_to users_path
end
我正在學習「Ruby方式」並獲得樂趣,但是,我有這個塊按預期工作,但我知道它可能會更好。有人能告訴我使用unless
的正確方法嗎?這在UsersController中。使用除非運算符
def destroy
User.find(params[:id]).destroy unless current_user.admin?
flash[:success] = "User destroyed."
redirect_to users_path
end
你寫代碼的方式實際上是最簡潔的;儘管你可能想要讓整個事物成爲一塊。這種方式當你打電話銷燬,「用戶被摧毀。」將不會被打印,並且redirect_to users_path將不會被調用,當該帳戶沒有被實際刪除時。
def destroy
unless current_user.admin?
User.find(params[:id]).destroy
flash[:success] = "User destroyed."
redirect_to users_path
end
end
這就是我一直在尋找的!我嘗試過(幾乎)。忘了把額外的「結束」,所以它沒有工作。謝謝您的幫助! – 2012-07-25 02:14:44
@GregWallace你確定你想要嗎?普通用戶可以銷燬用戶,而管理員不能? – xdazz 2012-07-25 02:30:06
正常用戶不能銷燬用戶,因爲除非用戶是管理員,否則不會呈現與要銷燬的命令的實際鏈接。還有其他機制只允許管理員刪除。你可能是對的,但它必須非常偷偷摸摸:-)我會研究你的想法。 – 2012-07-25 03:10:53
無論用戶是否被銷燬,您都將設置flash消息。
就你而言,你應該使用if。
def destroy
if current_user.admin?
User.find(params[:id]).destroy
flash[:success] = "User destroyed."
else
flash[:success] = "You can't destroy user."
end
redirect_to users_path
end
這看起來不錯,但它正在改變問題的邏輯。我假設這是OP想要的。 – 2012-07-25 02:14:18
當你要求「更好」的東西時,然後準備好改變你的邏輯。 – 2012-07-25 02:19:21
@AlexWayne但是我確定op的邏輯是錯誤的,它必須是'if current_user是admin',那麼他可以銷燬用戶。 – xdazz 2012-07-25 02:28:34
這是我能想到的所有有用的建議
def destroy
User.find(params[:id]).destroy
flash[:success] = "User destroyed."
redirect_to users_path
unless current_user.admin?
end
end
你能上「精益求精」的闡述後,使其作爲小型車?這種用法是什麼「不當」? – 2012-07-25 02:10:30
這就是我不知道的。這可以接受嗎? – 2012-07-25 02:11:53
只有當您想要顯示消息「用戶已銷燬」時,纔會接受這種情況,即使情況並非如此。如果是管理員用戶執行銷燬,你想要什麼行爲? (這種邏輯似乎倒退了) – 2012-07-25 02:13:13