![](/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.