Ruby on Rails 语法 [英] Ruby on Rails syntax
问题描述
这是你知道的问题之一,当你知道答案时会让你觉得自己很愚蠢,但我就是无法让这件事起作用,所以就这样吧.在 railstutorial.org 中,我正在尝试解决第 10 章末尾的练习 5,但以下代码是错误的,并且我尝试的每个变体(例如使用除非")都不起作用.如果当前用户不是管理员用户,我只想执行两行代码.我哪里出错了?
This is one of those questions that you just know is going to make you feel stupid when you know the answer, but I just can't get this thing working so here goes. In railstutorial.org I'm trying to solve exercise 5 at the end of chapter 10 but the following code is faulty, and every variation I try (using 'unless' for example) does not work. I simply want to execute two lines of code if the current user is not an admin user. Where am I going wrong?
def destroy
if !current_user.admin?
User.find(params[:id]).destroy
flash[:success] = "User destroyed."
end
redirect_to users_path
end
我混淆了当前用户和要删除的用户.我正在使用 Aditya 的代码,我确信它是正确的,但现在我收到一条无法运行测试"消息,表明我的测试中存在语法错误(如下).
I was confusing the current user with the user to be deleted. I am using Aditya's code, which I'm sure is correct, but now I am getting a 'can't run tests' message suggesting there is a syntax error in my tests (below).
describe "as an admin user" do
before(:each) do
admin = Factory(:user, :email => "admin@example.com", :admin => true)
test_sign_in(admin)
end
it "should not allow an admin user to destroy himself" do
lambda do
delete :destroy, :id => admin
end.should_not change(User, :count)
end
end
推荐答案
def destroy
if current_user.admin?
# If the current user IS admin
User.find(params[:id]).destroy # Find the user and destroy it
flash[:success] = "User destroyed." # Set the flash
end
redirect_to users_path # Go to users.
end
您的 if 条件没有意义.它是说如果用户不是管理员,请销毁.而我认为只有管理员才能摧毁用户.:)
Your if condition does not make sense. It was saying if the user is NOT an admin, destroy. Whereas i would imagine it would be that only admins can destroy users. :)
阅读 Railstutorial.org 第 10 章的练习 5 后,我有了更清晰的想法.:) 修改 destroy 动作,防止管理员用户销毁自己.
After reading Exercise 5 of Chapter 10 of the Railstutorial.org, I get a clearer idea. :) Modify the destroy action to prevent admin users from destroying themselves.
我知道这可能是作弊,但事实就是如此,我们这些傻瓜会在这里提供帮助!
I know this might be cheating but this is SO and we suckers are here to help!
def destroy
user = User.find(params[:id])
if user != current_user
user.destroy
flash[:notice] = "User destroyed".
else
flash[:error] = "Suicide is immoral."
end
redirect_to users_path
end
又一次编辑,只有管理员不能倒在剑上.
Yet another edit, ONLY admins are not allowed to fall on the sword.
def destroy
user = User.find(params[:id]) # Find the victim
if (user == current_user) && (current_user.admin?)
flash[:error] = "Suicide is immoral."
else
user.destroy
flash[:notice] = "User destroyed".
end
redirect_to users_path
end
这篇关于Ruby on Rails 语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!