Colton Van Bastelaere
Colton Van Bastelaere

Reputation: 345

How to use boolean conditions

So I'm obviously confused with boolean flow because I run into a problem each time. NOTE: I am teaching myself to program, you are all my only hope in learning! I am trying to define a method that checks if a user is an admin, so that I can display certain objects in views to ONLY admins simple enough...or not, for some reason it's not recognizing that I'm an admin (when I truly am, I've checked!). With this all being said, I am a newb so go easy on me!

helpers/sessions_helper is used by both my User and Blogpost models:

def current_user #determines if user is logged out or is the current user of the session/cookie of profile
  if (user_id = session[:user_id])
    @current_user ||= User.find_by(id: user_id)
  elsif (user_id = cookies.signed[:user_id])
    user = User.find_by(id: user_id)
    if user && user.authenticated?(cookies[:remember_token])
      log_in user
      @current_user = user
    end
  end
end

def current_user?(user)
  user == current_user
end

def is_an_admin
  if current_user && current_user.admin?
  end
end 

<div class="col-xs-12">
  <h1><%= @blogpost.title %></h1>
  <p><%= @blogpost.content %></p>
  <% if is_an_admin %>
    <%= link_to "Return to blog", blogposts_path %>
    <%= link_to "Edit Post", edit_blogpost_path, class: 'btn btn-primary' %> | 
    <%= link_to "Delete Post", blogpost_path(@blogpost), 
                method: :delete, data: {confirm: "Are you sure?"}, class: 'btn btn-danger' %>    
  <% else %>
    <%= link_to "Return to blog", blogposts_path %>
  <% end %>
</div>

I'm unsure if maybe I have the method in the wrong place? I have tried placing it inside my applications controller and my user controller to no avail. I must be missing something.

Upvotes: 0

Views: 146

Answers (1)

arieljuod
arieljuod

Reputation: 15838

Your sintax got messed up, but I think you're always returning nil on the is_an_admin method:

def is_an_admin
  if current_user && current_user.admin?
  end
end

It does nothing if the condition is true so it's always returning nil

Change it to something like:

def is_an_admin?
  current_user and current_user.admin? # or shorter: current_user.try('admin?')
end

Upvotes: 1

Related Questions