有人可以解释“授权所有权”(参见Railscasts)吗?

时间:2010-01-06 20:55:59

标签: ruby-on-rails security authorization

有人可以解释“授权所有权”吗?

我一直在浏览Railscasts' - 7 Security tips,并想知道“current_user.projects.find”是如何实现的?

# projects_controller.rb
def show
  @project = current_user.projects.find(params[:id])
end

谢谢!

3 个答案:

答案 0 :(得分:2)

调用类似“current_user”的方法首先需要某种身份验证系统。我建议您查看deviseomniauth(允许使用Facebook,Twitter等)。

关于current_user方法,正如我所说,它需要一个更复杂的身份验证系统和用户模型才有意义。但它被定义为ApplicationController.rb中的辅助方法,如下所示:

class ApplicationController < ActionController::Base
  protect_from_forgery

  helper_method :current_user

  private  
  def current_user  
    @current_user ||= User.find(session[:user_id]) if session[:user_id]  
  end
end

希望有所帮助!

答案 1 :(得分:0)

这定义了user.projects:

class User 
  has_many :projects
end

好吧,如果你的意思是实现,否则看看activerecord源代码:)

答案 2 :(得分:0)

实际上我意识到答案非常简单,并且是在帖子附带的railscast中。

最初使用此构造检索@project

def show
  @project = Project.find(params[:id])
end

所需要的只是通过执行

来使用activerecord关联
@project = current_user.projects.find(params[:id])