简体   繁体   中英

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

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?

params are always strings, use:

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

I don't recommend to_i , look why:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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