简体   繁体   English

如果语句始终返回true,则ruby on rails

[英]ruby on rails if statement always returns true

controller code: 控制器代码:

  def create

    if current_user.id != params[:friend_id]
      @return = { :curr_user_id => current_user.id, :params_id => params[:friend_id], :debug => 1 }
    else
      @return = { :curr_user_id => current_user.id, :params_id => params[:friend_id], :debug => 2 }
    end

    render :json => ActiveSupport::JSON.encode( @return )

  end

so current_user.id is 1 and params[:friend_id] is being passed via an ajax call and its value is also 1 因此current_user.id1,并且通过ajax调用传递了params[:friend_id] ,其值也为1

the problem is that it always returns true when it should return false in this case... is there anything that has to do with the number 1 being parsed as string instead of integer? 问题是,在这种情况下应返回false时,它总是返回true ...与数字1解析为字符串而不是整数有什么关系吗?

params are always strings, use: 参数始终是字符串,请使用:

if current_user.id != Integer(params[:friend_id])

I don't recommend to_i , look why: 我不建议to_i ,看看为什么:

"abc".to_i     # => 0 which is unexpected
Integer("abc") # => raises error, which is fine

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

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