2017-08-07 53 views
1

我在遇到以下代碼時遇到問題,請諒解它不是最乾淨的,但是這是關於第50次重構代碼的嘗試,因此它工作正常。意外的tIVAR,預期的keyword_end String.Format

@userId = params[:id] 
@user = User.where("id=" + @userId).first() 
@expertProfilePhotoName = @user.profile_file_name 
@expertProfilePhotoSize = @user.profile_file_size 
@message = "%s\n%s" @expertProfilePhotoName, @expertProfilePhotoSize 

我不斷得到錯誤意外tIVAR,預期keyword_end,並不確定爲什麼我得到它。我嘗試了各種各樣的選擇,但似乎無法弄清楚。

回答

2

你可以嘗試用:

@user = User.where('id = ?', @userId).first() 

如果您where語句結合的@userId的價值,而不是串接它。

此外,如果你想找到它的ID的用戶屬性,你可以使用find

@user = User.find(@userId) 

而且假如你希望插值@expertProfilePhotoName@expertProfilePhotoSize那麼你可以做:

@message = "#{@expertProfilePhotoName}\n#{@expertProfilePhotoSize}" 
+0

感謝上查找尖一切都將正常工作! 問題與最後一行有關。我不太瞭解Ruby on Rails中的sprintf,但我已經用「#{expertProfilePhotoName}#{@ expertProfilePhotoSize}」得出結論「 –

1

塞巴斯蒂安答案是好的,他的觀點尤其是關於你的方法對安全POV非常重要,應該遵循。

但是,要直接解決您收到的錯誤的來源,它在最後一行。你有一個字符串,然後直接跟一個實例變量,所以它拋出異常syntax error, unexpected tIVAR, expecting end-of-inputIVAR ==實例變量)。

如果您嘗試使用sprintf,那麼這兩個對象應該用逗號分隔,因爲它們是方法參數,但是您也缺少sprintf方法調用本身。如果你改變了最後一行此

@message = sprintf "%s\n%s", @expertProfilePhotoName, @expertProfilePhotoSize 

也可以寫成

@message = format "%s\n%s", @expertProfilePhotoName, @expertProfilePhotoSize 
+1

謝謝,我正在關注其他一些我在其他答案中看到的其他示例並沒有找到完整的語法。我用逗號嘗試過,但我不知道方法調用的名字!我認爲幕後發生了一些奇怪的紅寶石魔法 –

+0

很好的解釋,也是sprintf的澄清。 –

相關問題