繁体   English   中英

如果条件为假,则Ruby如果有条件地奇怪地运行了一些代码

[英]Ruby if conditional weirdly appears to run some code when the condition is false

我有一个设置,其中我将Devise用作Rails应用程序的主要身份验证处理程序,并且有时它会以与调用Type.where( name: "bob" )相同的方式拉出ActiveRecord关系而不是记录Type.where( name: "bob" )

为了解决此问题(我没有在Devise上花费很多时间,也没有太多的空闲时间来探索它),我只是想确保登录已检查并更正了这一点,所以我写了一个像这样的部分:

def authenticate_user_with_assignment!
    authenticate_user!
    logger.debug("User is #{current_user.inspect}")
    if ( current_user.is_a?(ActiveRecord::Relation) )
       logger.debug ("It is a relation!")
       current_user = current_user.first
    else
       logger.debug ("Not a relation.")
    end
    logger.debug("User is #{current_user.inspect}")
    # do some other stuff
end

我得到这样的输出:

User is #<User id: 1, email: "admin@testaddress.com" ... etc >
Not a relation.
User is nil

如果我注释掉current_user = current_user.first行,我得到的是:

User is #<User id: 1, email: "admin@testaddress.com" ... etc >
Not a relation.
User is #<User id: 1, email: "admin@testaddress.com" ... etc >

因此,某种程度上,它似乎忽略了我的if条件中的logger语句,但正在运行分配。 我不知道为什么会这样-有什么想法吗?

current_user = current_user.first

这将创建一个局部变量,该局部变量会遮盖current_user方法。 只要解析器注意到声明了局部变量,就创建它们,无论是否实际执行赋值,因此,如果if条件为false,则声明局部变量current_user ,然后为nil 您需要改为执行current_user=方法:

self.current_user = current_user.first

如果您没有这样的方法,请定义它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM