Rails 3.1只有用户可以编辑他们的个人资料

时间:2011-07-08 09:53:18

标签: ruby-on-rails ruby-on-rails-3 authentication

我正在通过做和测试来慢慢地学习rails,但是我遇到了障碍。我有一个简单的rails 3.1应用程序,并有一个简单的用户注册/登录过程工作。我没有使用设计,因为我宁愿自己学习如何做。

目前,用户可以注册,登录和注销。但我希望他们能够编辑他们的个人资料。目前,任何用户都可以转到用户/ 1 /编辑/即使他们的ID未设置为1.我如何检查current_user是否与网址的匹配?我知道我需要在我的users_controller的编辑操作之前进行某种过滤。

这是我目前所拥有的

users_controller.rb

before_filter :is_owner, :only => [:edit, :update, :destroy]

application_controller.rb

helper_method :is_owner
def is_owner
end

我的is_owner函数应该包含什么内容?

2 个答案:

答案 0 :(得分:3)

我猜你的问题在于从URL获取参数。这可以使用params数组来完成:

params[:id]

有了这个(取决于您的路由配置!),您可以执行类似

的操作
def is_owner?
  current_user.id == params[:id]
end

答案 1 :(得分:2)

Fuzzyalej显然比我的速度更快;-),所以我只能建议你一些更详细的函数形式。 (他的回答绝对正确)

您已在ApplicationController中定义了过滤器方法,但在这种情况下,只比较'id'参数可能会产生误导,因为在其他操作中,'id'可能描述文档(例如)而不是用户。 如果在UsersController中定义过滤器函数(只是使其成为私有函数)可能会更安全

就个人而言,我经常在动作中直接使用类似的规则,但使用过滤器可能更干。

我会用这种方式定义方法'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