Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/53.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何从控制器修改用户的一个属性?_Ruby On Rails_Ruby On Rails 3_Controller - Fatal编程技术网

Ruby on rails 如何从控制器修改用户的一个属性?

Ruby on rails 如何从控制器修改用户的一个属性?,ruby-on-rails,ruby-on-rails-3,controller,Ruby On Rails,Ruby On Rails 3,Controller,在我的应用程序中,普通用户应该能够点击按钮,成为超级用户。在控制台中,我可以获取一个用户,然后执行user.super=true,user.save,然后它就可以工作了。我将下面的代码放在我的控制器中,但它会闪烁“无法工作”错误,而不是成功更改用户。我怎么修理它 def become_super user = current_user user.super = true if user.save flash[:success] = "You are super

在我的应用程序中,普通用户应该能够点击按钮,成为超级用户。在控制台中,我可以获取一个用户,然后执行
user.super=true
user.save
,然后它就可以工作了。我将下面的代码放在我的控制器中,但它会闪烁“无法工作”错误,而不是成功更改用户。我怎么修理它

def become_super
    user = current_user
    user.super = true
    if user.save
      flash[:success] = "You are super"
    else
      flash[:error] = "That didn't work"
      redirect_to apply_path
    end

正如在评论中提到的,您可能在验证方面有问题

您可以完全跳过验证(毕竟您只想让它们成为超级用户)

或者您也可以让用户知道发生了什么样的验证错误()


请注意,super有OO的意思,应该避免使用

很可能是验证失败。您可以检查else块中的
user
是否有错误吗?或者您可以直接使用
if current\u user.update\u attributes(:super=>true)
。但它将再次通过验证检查。@jvnill,如何检查错误?我查看了日志,但它只是说回滚事务,没有解释原因。试试
user.save
因此会引发异常,但请确保在找出问题所在后将其切换回。是否允许用户在不输入密码的情况下编辑其数据?然后您可以添加
验证:密码、状态:true、:on=>:创建
current_user.update_attribute(:super, true) # please note, singular!
user.super = true
if user.save
  # as before
else 
  flash[:error] = "Please fix your user record first, there are " + 
                  "validation errors: #{user.errors.full_messages.join(", ")}"
  redirect_to apply_path
  # Note: Do not use this pattern for normal CRUD actions!
end