实战Hilog笔记三:@current_user/logged_in?/require_login/editable?

1,在ApplicationController里添加几个辅助方法:
class ApplicationController < ActionController::Base
  session :session_key => '_hilog_session_id'
  before_filter :load_defaults
  helper_method :logged_in? 

  protected

    def load_defaults
      @current_user =
        if logged_in?
          User.find(session[:user_id])
        else
          nil
        end
    end
    
    def logged_in?
      session[:user_id]
    end
    
    def require_login
      redirect_to(new_session_url(:go_after => request.request_uri)) and return false unless session[:user_id]
    end

end

load_defaults得到当前登录的用户@current_user
helper_method让logged_in?方法可以在rhtml页面里使用
require_login是一些需要登录权限才能操作的action的before_filter

2,在Topic模型类里添加editable_by?方法:
class Topic < ActiveRecord::Base
  belongs_to :user
  
  def editable_by?(account)
    account && (account.id == user.id )
  end
  
end

这样可以在rhtml页面和controler里判断topic是否可以被@current_user编辑和删除

你可能感兴趣的:(Blog,Flash,ActiveRecord,Go)