![](/img/trans.png)
[英]Rails Tutorial (M. Hartl) Chapter 9 (9.2.1 : Requiring logged user) Error: undefined method `user_id'
[英]Undefined method 'logged_in_user' for RelationshipsController in Ruby on Rails Tutorial
這有點奇怪。 我正在遍歷ruby on rails教程的第十二章(以供參考: https : //www.railstutorial.org/book/following_users ),並通過了所有測試,到達了12.2.4節。 然后,我執行命令rails generate controller Relationships
並在清單12.30和12.31中准確輸入了代碼,以嘗試使關系控制器測試通過,但是出現以下錯誤:
ERROR["test_destroy_should_require_logged-in_user", RelationshipsControllerTest, 2015-11-13 11:07:25 +0000]
test_destroy_should_require_logged-in_user#RelationshipsControllerTest (1447412845.16s)
NoMethodError: NoMethodError: undefined method `logged_in_user' for #<RelationshipsController:0x000000044f5bd8>
test/controllers/relationships_controller_test.rb:14:in `block (2 levels) in <class:RelationshipsControllerTest>'
test/controllers/relationships_controller_test.rb:13:in `block in <class:RelationshipsControllerTest>'
test/controllers/relationships_controller_test.rb:14:in `block (2 levels) in <class:RelationshipsControllerTest>'
test/controllers/relationships_controller_test.rb:13:in `block in <class:RelationshipsControllerTest>'
ERROR["test_create_should_require_logged-in_user", RelationshipsControllerTest, 2015-11-13 11:07:25 +0000]
test_create_should_require_logged-in_user#RelationshipsControllerTest (1447412845.22s)
NoMethodError: NoMethodError: undefined method `logged_in_user' for #<RelationshipsController:0x00000004db9990>
test/controllers/relationships_controller_test.rb:7:in `block (2 levels) in <class:RelationshipsControllerTest>'
test/controllers/relationships_controller_test.rb:6:in `block in <class:RelationshipsControllerTest>'
test/controllers/relationships_controller_test.rb:7:in `block (2 levels) in <class:RelationshipsControllerTest>'
test/controllers/relationships_controller_test.rb:6:in `block in <class:RelationshipsControllerTest>'
為什么看不到用戶控制器中的logging_in_user方法? 我可以把它放在
class RelationshipsController < ApplicationController
before_action :logged_in_user
def create
user = User.find(params[:followed_id])
current_user.follow(user)
redirect_to user
end
def destroy
user = Relationship.find(params[:id]).followed
current_user.unfollow(user)
redirect_to user
end
private
# Confirms a logged-in user.
def logged_in_user
unless logged_in?
store_location
flash[:danger] = "Please log in."
redirect_to login_url
end
end
end
並且測試通過了,但是這種違反貫穿本教程的“不要重復自己”原則。 任何想法出什么事了嗎?
那是方法logged_in_user
在上UsersController
或ApplicationsController
? 如果在UsersController
,則由於層次繼承,將無法訪問它。 嘗試將該方法放入ApplicationsController
,然后旋轉它。
這樣做將使UsersController
和RelationshipsController
可以訪問此方法,因為它們都繼承自ApplicationsController
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.