我正在通过做和测试事情来慢慢学习rails,但是我遇到了一个障碍。我有一个简单的rails 3.1应用程序,并有一个简单的用户注册/登录过程工作。我不使用设计,因为我宁愿自己学习如何做。
当前用户可以注册、登录和注销。但我希望他们能够编辑自己的个人资料。目前任何用户都可以进入users/1/edit/,即使他们的ID没有设置为1。我如何检查,看看是否current_user匹配的url?我知道我需要在我的users_controller的编辑动作上设置一些before过滤器。
这是我目前的资料
users_controller.rb
before_filter :is_owner, :only => [:edit, :update, :destroy]
application_controller.rb
helper_method :is_owner
def is_owner
end
在我的is_owner函数应该是什么?
我猜你的问题在于从URL获取参数。这可以通过参数数组来实现:
params[:id]
有了它(取决于你的路由配置!),你可以做像
这样的事情def is_owner?
current_user.id == params[:id]
end
Fuzzyalej显然比我打字更快;-),所以我只能建议您使用更详细的函数形式。(他的回答绝对正确)
您已经在ApplicationController中定义了过滤器方法,但是在这种情况下,只比较'id'参数可能会产生误导,因为在其他操作中,'id'可能会描述文档(例如)而不是用户。如果您在UsersController中定义过滤器函数(只需将其设置为私有函数),可能会更安全
就我个人而言,我经常将类似的规则直接放在动作中,但使用过滤器可能更DRY。
我将这样定义'edit', 'update'和'destroy'方法:(也许你会喜欢它)
def edit # and 'update', and 'destroy'
@user = User.find(params[:id])
render_forbidden and return unless can_edit?
# ...and the rest of the action
end
private
def can_edit?
current_user.is_admin? || current_user == @user
end
# This one usually is defined in ApplicationController, as I use it often
def render_forbidden
respond_to do |format|
format.html { render :action => "errors/forbidden", :status => 403 }
#...
end
true
end