路由根以显示登录用户的用户post和未登录的静态页面
故事:未登录的用户应该看到一个欢迎静态页面,当他登录时,他应该看到他的博客post列表。
我想正确的方法是将root
路由到列出所有用户post然后检查身份validation的操作。 如果用户未登录,则呈现欢迎页面?
我需要帮助为posts控制器编写一个动作,该控制器显示登录用户的post。
routes.rb中:
root :to => "posts#index"
post_controller.rb
class PostsController < ApplicationController before_filter :authenticate_user! def index @posts = current_user.posts.all end end
如果用户未登录,则beforefilter捕获并重定向某处(登录?错误消息?)。 否则,将调用index方法并呈现索引视图。 如果你推出另一个身份validation,你需要调整和/或编写自己的帮助程序,这可以开箱即用,例如:
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
我有这个问题,但不想重定向(添加延迟和更改url)所以我决定在Rails 3中的以用户为中心的路由中建议的约束或使用lambdas for Rails 3路由约束中提到的范围路由
约束
root :to => "landing#home", :constraints => SignedInConstraint.new(false)
范围路线
scope :constraints => lambda{|req| !req.session[:user_id].blank? } do # all signed in routes end