且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

路由根以显示登录用户的用户帖子和未登录的静态页面

更新时间:2023-11-30 17:49:58

routes.rb:

routes.rb:

root :to => "posts#index"

post_controller.rb

post_controller.rb

class PostsController < ApplicationController
  before_filter :authenticate_user!

  def index
    @posts = current_user.posts.all
  end
end

如果用户未登录,则过滤器捕获此信息并重定向到某处(登录?错误消息?)。否则,将调用index方法并呈现索引视图。
如果您推出另一个身份验证,您需要调整和/或编写自己的帮助程序,这将是开箱即用的设计。类似这样的事情:

If the user is not logged in, the before filter catches this and redirects somewhere (login? error message?). Otherwise the index method is called and the index view rendered. This would work out of the box with devise, if you roll another authentication you need to adapt and/or write your own helpers, e.g. something like this:

application.html.erb

application.html.erb

class ApplicationController < ActionController::Base
  protect_from_forgery

  helper_method :current_user
  helper_method :user_signed_in?

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

    def user_signed_in?
      return 1 if current_user 
    end

    def authenticate_user!
      if !current_user
        flash[:error] = 'You need to sign in before accessing this page!'
        redirect_to signin_services_path
      end
    end 
end