ruby on rails if语句总是返回true

时间:2012-09-15 18:53:15

标签: ruby-on-rails ruby ruby-on-rails-3 controller conditional

控制器代码:

  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

所以current_user.id 1 params[:friend_id]通过ajax调用传递,其值也 1

问题是它在这种情况下应该返回false时总是返回true ...是否有任何与被解析为字符串而不是整数的数字1有关?

1 个答案:

答案 0 :(得分:6)

params 总是字符串,使用:

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

我不推荐to_i,看看为什么:

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