我试图使用before_filter来限制对某些操作的访问,这似乎很容易。不知何故,ApplicationController无法识别current_user是用户编辑操作的所有者。当我关闭过滤器时,控制器正确地将current_user路由到其编辑视图信息。这是代码。
从用户控制器(views/questions/index.html.erb
)链接到呼叫编辑操作:
<%= link_to "Edit Profile", edit_user_path(:current) %>
ApplicationController(我只发布了我认为影响这个的代码,但如果需要可以发布整个内容)。
class ApplicationController < ActionController::Base
def require_owner
obj = instance_variable_get("@#{controller_name.singularize.camelize.underscore}") # LineItem becomes @line_item
return true if current_user_is_owner?(obj)
render_error_message("You must be the #{controller_name.singularize.camelize} owner to access this page", root_url)
return false
end
end
和before_filter
class UsersController < ApplicationController
before_filter :require_owner, :only => [:edit, :update, :destroy]
#...
end
我只是从ApplicationController#require_owner操作中获取错误消息。
更新:link_to提供此地址:localhost:3000 / users / current / edit
答案 0 :(得分:1)
好的,这是我发布的第二个赏金问题,然后自己回答。两次我都在我的赏金帖子的一小时内找到答案。哈。
我只是更改了之前的过滤方法,以使其工作。我离开了应用程序控制器,因为它在上面的代码中但在UsersController中(唯一一个没有合作的)我执行了以下操作:
before_filter :require_user, :only => [:edit, :update, :destroy] # all actions require user to be logged in
before_filter :init_data # create a member variable called @post, initialized based on the action
before_filter :require_user_owner, :only => [:edit, :update, :destroy] #edit, update, and destroy actions require ownership
然后
private
def require_user_owner
obj = instance_variable_get("@#{controller_name.singularize.camelize.underscore}") # LineItem becomes @line_item
return true if current_user.id == @user.id
render_error_message("You must be the #{controller_name.singularize.camelize} owner to access this page", root_url)
return false
end
似乎这样做了。
答案 1 :(得分:0)
我觉得current_user_is_owner?(obj)
电话有问题。要证明这一点,请将代码修改为:
def require_owner
# LineItem becomes @line_item
obj = instance_variable_get("@#{controller_name.singularize.camelize.underscore}")
if current_user_is_owner?(obj)
return true
else
render_error_message("You must be the #{controller_name.singularize.camelize} owner to access this page", root_url)
return false
end
end
您可能希望粘贴current_user_is_owner?
方法。
希望它有所帮助。