Routing root to display user's posts for logged in users and static page for non-logged in
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.
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?
I need help with writing an action for the posts controller which displays posts for the logged in user.
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
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
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
I had this problem but didn't want a redirect (adds delay and changes url) so I'm deciding between constraints suggested in User-centric Routing in Rails 3 or scoped routes mentioned in Use lambdas for Rails 3 Route Constraints
Constraints
root :to => "landing#home", :constraints => SignedInConstraint.new(false)
Scoped routes
scope :constraints => lambda{|req| !req.session[:user_id].blank? } do
# all signed in routes
end
精彩评论