How to have root view when user is not logged in rails?

余生颓废 提交于 2020-01-07 03:16:13

问题


I am building a rails app and I use Devise for authentication. I want to show a product first page when user comes to www.mydomain.com instead of www.mydomain.com/users/sign_in which is devise default!

I will also want to show a different root view when user is logged in. This feels like a very common use case, is there a easy way to do this? Is this there in documentation or can anyone help me with this?


回答1:


You can use the authenticate route helper to add a constraint on the routes so that they are only available to logged in users:

Rails.application.routes.draw do
  devise_for :users

  authenticated :user do
    root 'secret#index', as: :authenticated_root
  end

  root "home#index"
end

The advantage over @Sergio Tulentsev's answer is that this does not cause a redirect or require any additional logic in the controller.

However the reason your app is redirecting to /users/sign_in is most likely that you are using before_action :authenticate_user! in your ApplicationController so that the controller handling the root path is requiring authentication and redirecting to the sign in. You can fix this (while retaining a secure by default setup) by skipping the callback:

class HomeController < ApplicationController
  skip_before_action :authenticate_user!
  # ...
end

This applies to any controller that should not require authentication. You can skip specific actions by using the only and except options. Just remember that whitelists are more secure than blacklists.




回答2:


I'd do this way, have a single route for root path:

# routes.rb
root to: 'home#index'

Then check for current user and decide which page to show.

class HomeController < ApplicationController
  def index
    if current_user
      redirect_to some_page_path
      # or render some content directly in this response
      render :some_view
    else # no logged-in user
      # same, render or redirect
    end
  end
end


来源:https://stackoverflow.com/questions/43429845/how-to-have-root-view-when-user-is-not-logged-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!