2012-10-25 33 views
1

我試圖更新數據庫中的一些數據,但我得到這個錯誤:未定義的方法`is_current」爲#:在紅寶石<的ActiveRecord ::關係0x38622a8>在軌道上的更新數據

undefined method `is_current' for #<ActiveRecord::Relation:0x38622a8> 

我控制器:

@user = User.where("user_id = #{user_id} and is_current = 1") 

if @user.nil? 
    puts"xxxxxxxxxxxxxxxxxxxxxxxxxxx" 
else 
    @user.is_current = 0 
    @user.to = Time.now 
    @user.save 
end 
+2

將您的用戶模型代碼 – HungryCoder

+0

和架構用於用戶表 – ck3g

回答

5

User.where返回一個數組。之後你需要先說。另外,不要在沒有逃避論點的地方使用字符串。您的查詢不安全,並且對SQL注入開放。

@user = User.where(user_id: user_id, is_current: 1).first 
+0

完美解決了我的問題。感謝幫助。 –

+2

爲了完整起見,你可以使用預先準備的語句,如果你必須使用一個字符串出於某種原因:'User.where('user_id =?和is_current = 1',user_id)' – x1a4

+0

好吧,我會的,感謝您的幫助。 –

1

嘗試寫在型號查詢,這是很好的做法,所以你可以做

@user = User.where("user_id = #{user_id} and is_current = 1") 

在你的模型

@user = User.user_is_current(user_id,1) # two argument 1) user_id and 2) is_current value 

更換

def user_is_current(user_id,is_current) 
    where(user_id: user_id, is_current: is_current) 
end 

它會給數組提供數據,以便您可以編寫

@user = User.user_is_current(user_id,1).first 
+0

感謝dipak的建議。 –

相關問題