路由根以显示登录用户的用户帖子和未登录的静态页面 [英] Routing root to display user's posts for logged in users and static page for non-logged in

查看:149
本文介绍了路由根以显示登录用户的用户帖子和未登录的静态页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

故事:未登录的用户应该会看到一个欢迎静态页面,当他登录时,他应该会看到他的博客帖子列表。

Story: A non logged in user should see a welcome static page and when he's logged in he should see a list of his blog posts.

我认为是正确的这样做的方法是将 root 路由到列出所有用户帖子然后检查身份验证的操作。如果用户没有登录,那么它会呈现欢迎页面吗?

I suppose the right way to do this is to route root to the action that lists all the user's posts which then checks for authentication. If the user isn't logged in then it renders the welcome page?

我需要帮助为posts控制器编写一个动作,该控制器显示登录用户的帖子。

I need help with writing an action for the posts controller which displays posts for the logged in user.

推荐答案

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

这篇关于路由根以显示登录用户的用户帖子和未登录的静态页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆