2017-06-05 17 views
0

我希望能夠將我的用戶對象傳遞給另一個類進行驗證。基本上我做這樣的事情Rails在傳遞到類後激活記錄爲空

我的控制器:

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

/型號

Class UserHelper 

def initialize(user) 
    @user = user 
end 

def isAdmin 
    if @user.isadmin 
    true 
    end 
    nil 
end 

將在控制器語句總是解決爲零,即使我知道的記錄是正確的。我可以不正確地將ActiveRecords傳遞給類嗎?

有沒有人有任何想法,爲什麼這可能會發生?

編輯

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|[email protected]|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); 
+0

'isAdmin'將因爲您告訴它而始終返回'nil'。如果'nil'應該是else響應,那麼重構你的'isAdmin'方法來使用'if ... else ... end'。對於'ActiveRecord'布爾值,標準約定是調用「布爾方法」,而不是'@ user.isadmin',它將是'@ user.isadmin?'(末尾帶有問號)。終於是什麼'userfnc'?應該可能是「app/models/user.rb」或「app/helpers/user_helper.rb」 – engineersmnky

回答

1

有相當多的代碼改進,你可以使用你的代碼。

至於你的問題,你的套子可能會讓你受傷。檢查你的桌子。您的字段可能被稱爲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 

但是...... Rails的標準是在這種情況下使用過濾器。取而代之的是,把它放在一個過濾器方法中。

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

請參閱上面的修改 – jacksonecac