簡體   English   中英

如果語句始終返回true,則ruby on rails

[英]ruby on rails if statement always returns true

控制器代碼:

  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.id1,並且通過ajax調用傳遞了params[:friend_id] ,其值也為1

問題是,在這種情況下應返回false時,它總是返回true ...與數字1解析為字符串而不是整數有什么關系嗎?

參數始終是字符串,請使用:

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

我不建議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