gpt4 book ai didi

ruby-on-rails - 路由 root 以显示登录用户的用户帖子和未登录用户的静态页面

转载 作者:数据小太阳 更新时间:2023-10-29 08:06:06 25 4
gpt4 key购买 nike

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

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

我需要帮助为帖子 Controller 编写一个操作,该操作为登录用户显示帖子。

最佳答案

路线.rb:

root :to => "posts#index"

post_controller.rb

class PostsController < ApplicationController
before_filter :authenticate_user!

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

如果用户没有登录,before 过滤器会捕获它并重定向到某个地方(登录?错误消息?)。否则调用 index 方法并呈现索引 View 。这将与设计开箱即用,如果您滚动另一个身份验证,您需要调整和/或编写您自己的助手,例如像这样:

应用程序.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

关于ruby-on-rails - 路由 root 以显示登录用户的用户帖子和未登录用户的静态页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5591330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com