Rails - Using different views for anonymous vs. logged in users: Bad idea?

83 Views Asked by At

My admin accounts are user accounts with a simple boolean set to true. Works fine for now, I can control functionality with if statements in the views, example:

 <td><% if current_user.admin? || current_user == user %>
   <%= link_to "Edit", edit_user_path(user) %>  
    <% end %></td>

Some resources are off limits to anonymous users, and they get redirected to the login page if they try and select those links. But other resources (like a list of all the articles on the site), I want both those with a session and those without to see. The problem of course is that a user with no session will throw an error, because there is no current_user if you don't have a session. So I decided to divide up the world into the 2 parts. When you hit the index.html.erb for 'articles', this is all that in there:

 <% if current_user == nil %>
      <%= render "anonindex" %>
      <% else %>
      <%= render "authindex" %>
  <% end %>

My question is, am I making a long term design mistake by doing this? Am I eventually going to need to implement a roles based system, or is it feasible to differentiate user privileges based on boolean operators, and keep the users with no session in a completely separate sandbox? Its working great thus far, but I worry I'm going down a path that will require a total rebuild later.

1

There are 1 best solutions below

0
On BEST ANSWER

You don't actually have to check this thing in views. You can check this thing in Controller, and can take the appropriate out there:

class YourController < ApplicationController
  before_action :check_user_logged_in, only: [:index, :your_desired_method]
end 

And then in check_user_logged_in method, you can see if a user is logged in, send him to the desired place, otherwise redirect him to the log in page.

def check_user_logged_in
  redirect_to log_in_path unless current_user
end