Rails Active record null after passed to class



我希望能够将我的用户对象传递到另一个类以进行验证。基本上我做了

之类的事情

我的控制器:

def new
  user = User.find(1)
  logger.info "#{user.id}, #{user.name}, #{user.isadmin}"
  #The above is logged with 1, test, true
  uhelper = UserHelper.new(user)
  if !uhelper.isAdmin
    #Only admins can access this page
    redirect_to root_path
  end
end

在App/Models

Class UserHelper
def initialize(user)
  @user = user
end
def isAdmin
  if @user.isadmin
    true
  end
    nil
end

即使我知道记录是正确的,控制器中的if语句始终可以解决。我不能正确地将ActivereCord转到这样的课程吗?

有人有任何想法为什么会发生这种情况吗?

编辑

undefined method `isadmin' for nil:NilClass
app/models/userfnc.rb:14:in `isAdmin'
app/controllers/rosters_controller.rb:12:in `index'
sqlite> select * from users;
1|testuser|test@test.com|20170601|20170601|1
sqlite> .schema users
CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar DEFAULT NULL, "email" varchar DEFAULT NULL, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL, "isadmin" boolean);

您可以使用很多代码改进。

关于您的问题,您的套管可能会得到您。检查您的桌子。您的字段可能称为isadmin而不是isAdmin

至于您的代码改进,以下是可以帮助您的:

def isAdmin
  if @user.isAdmin
    true
  end
    nil
end

您可以用一行来完成此操作:

def isAdmin
  @user.isAdmin
end

这个位,

uhelper = UserHelper.new(user)
if !uhelper.isAdmin
  #Only admins can access this page
  redirect_to root_path
end

当您具有这样的简单表达式时,有时更容易将其简化为一行:

uhelper = UserHelper.new(user)
redirect_to root_path unless uhelper.isAdmin

但是... 在这种情况下,将使用过滤器。将其放在过滤器方法中,而不是完全放这个。

class MyController
  before_filter :check_admin
  ...
  ...
  private
  def check_admin
    redirect_to root_path unless user.isAdmin
  end
end

相关内容

最新更新