开发者

Can someone explain "Authorizing Ownership" (see Railscasts)?

Can someone explain "Authorizing Ownership"?

I've been going through the Railscasts' - 7 Security tips, and was wondering how is the "current_user.projects.find" implemented?

# projects_controller.rb
def show
  @project = current_user.开发者_Python百科projects.find(params[:id])
end

Thank you!


Calling a method like "current_user" will first require some kind of authentication system. I recommend you look into devise or omniauth (allows for Facebook, Twitter, etc).

With regards to the current_user method, as I said, it requires a more complex authentication system and User model for it to make sense. But it is defined as a helper method in ApplicationController.rb like so:

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

Hope that helps!


This defines user.projects:

class User 
  has_many :projects
end

Well if you mean that with implemented, otherwise take a look at activerecord source code :)


Actually I realized that the answer is quite simple, and it is in the railscast attached to the post.

Initially the @project was retrieved with this construct:

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

All that was needed was to use the activerecord association by doing

@project = current_user.projects.find(params[:id]) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜