2016-08-28 17 views
2

我試圖將用戶的角色從standard更改爲admin。這是我迄今爲止所嘗試的,我相信我很接近。爲什麼「user.role.save」在Rails中返回NoMethodError?

User.last 
#=> #<User id: 3, email: "[email protected]", role: 0> 

# set variable user to User.last 
user = User.last 

user.role 
#=> "standard" 

user.role=1 
#=> 1 

user.role 
#=> "admin" 

user.role.save 

NoMethodError: undefined method `save' for "admin":String

還有很多更紅寶石輸出,但是這似乎是一個重要的線。很顯然,我將角色從standard改爲admin,但我不確定如何保存它。

+2

你應該調用'user.save' –

+1

你的模型對象是'user'而不是'user.role',後者是_attribute_,需要在模型對象上調用'save' - 更多解釋http:// stackoverflow。/39178261/rails4-how-to-assign -a-nested-resource-id-to-another-resource/39178291#39178291 – kiddorails

+0

Ahhhhhh所以我在對象'user'上調用'save'而不是在'role'。 也謝謝你,工作。 – SinGar

回答

2

方法鏈並不總是返回你認爲他們做的事。如有疑問,請將事情分開!

在你的情況下,user.role返回一個String,它沒有實現#save方法。相反,您想要調用模型的User#保存方法。所以:

user = User.last 
user.role = 1 
user.save 

當然,還有其他方法可以做到這一點,但上面的例子應該能解決你的問題,而這也解釋了爲什麼原代碼,提出了NoMethodError例外。

相關問題