1

I am trying to implement some conditions in views like "Edit" and "Delete" button should be visible only if current user is Admin for my application. When i try to <% if current_user.is_admin %> in my articles/index.html.erb page, I get undefined method "is_admin" error.

Can not I use current_user method of devise within article index page to get user? Please suggest me how to get user and then check if user is admin or not.

My code file are below:

articles/index.html.erb

<%- model_class = Article -%>
<div class="">
  <h1><%=t '.title', :default => model_class.model_name.human.pluralize %></h1>
</div>

<div style="border: 1px solid #1763A4;border-radius: 4px 4px 4px 4px;margin: 0 0 20px; padding: 20px 20px 10px;">

    <% @articles.each do |article| %>
    <div style="border: 1px solid #51702E;border-radius: 4px 4px 4px 4px;margin: 0 0 20px; padding: 20px 20px 10px;">
       <div style="color:#51702E"><h2><%= article.title %></h2></div>
       <div style="color:#666666"> <%= article.created_at %></div> 
       <% if current_user.is_admin %> 
       <div> <%= truncate(article.body, :length => 500, :separator => ' ') %></div>  
     <%= link_to "edit",edit_article_path(article), :class => 'btn btn-warning btn' %>
     <%= link_to "delete",article_path(article),:method => :delete,:confirm => 'Are you sure?',:class => 'btn  btn-danger' %>
     <% end %>
     <%= link_to "VIEW MORE...",article_path(article), :class => 'btn btn-primary' %> 
     </li>
     </div>
    <% end %>
<%= link_to "Create new Article", new_article_path, :class => 'btn btn-large btn-primary' %>

articles_controller.rb

class ArticlesController < ApplicationController
    def index
        @articles = Article.all
    end

    def show
      @article = Article.find(params[:id])
    end

    def new
      @article = Article.new
    end

    def create
      @article = Article.new(params[:article])

      @article.save
      redirect_to article_path(@article)
    end

    def destroy
      @article = Article.find(params[:id])
      @article.destroy
      redirect_to action:  'index'  
    end

    def edit
      @article = Article.find(params[:id])
    end

    def update
      @article = Article.find(params[:id])
      @article.update_attributes(params[:article])
      flash.notice = "Article '#{@article.title}' Updated!"
      redirect_to article_path(@article)
     end
end

model : article.rb

class Article < ActiveRecord::Base
   attr_accessible :title, :body
   has_many :comments
   belongs_to :user
end

user.rb

class User < ActiveRecord::Base
    has_many :articles
    has_many :comments
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :username, :email, :password, :password_confirmation, :remember_me
   attr_accessible :title, :body
end

User table

 create_table "users", :force => true do |t|
    t.string   "email",                  :default => "", :null => false
    t.string   "encrypted_password",     :default => "", :null => false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          :default => 0
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.boolean  "is_admin"
    t.boolean  "is_active"
    t.datetime "created_at",                             :null => false
    t.datetime "updated_at",                             :null => false
    t.string   "username"
  end

2 Answers 2

1

from https://github.com/plataformatec/devise/wiki/How-To:-Add-an-Admin-role

If the page could potentially not have a current_user set then:

if current_user.try(:admin?)
  # do something
end

or maybe in your case

if current_user.try(:is_admin)
  # do something
end

This should work, when there is no current user (ie. not logged in)

4
  • hi scones, It works for me, many many thanks,today you saved me :) but i could not understand why did it work and not current_user.is_admin.Could you please explain it bit. Apr 4, 2013 at 19:45
  • as i mentioned, the user might not be logged in. the try function only check if the object left of it is nil, if not the function in the parentheses will be called, otherwise not.
    – scones
    Apr 4, 2013 at 19:47
  • hi scones , how i can contribute to your reputation or badges? Apr 4, 2013 at 19:53
  • @VSiingh if you want to, you may click the checkmark to the left to accept the answer. additionally you can upvote the answer by clicking the up arrow next to it. You should definitally have a look at the about section: stackoverflow.com/about
    – scones
    Apr 4, 2013 at 20:01
0

Does your User model have an admin attribute?

If not tou need to define one, e.g

class AddAdminToUsers < ActiveRecord::Migration
  def self.up
    add_column :users, :admin, :boolean, :default => false
  end

 def self.down
   remove_column :users, :admin
 end
end

Then run rake db:migrate

You should then be able to check if a user is admin by calling:

current_user.admin?

There are other options to do this as well in devise, check them out here

https://github.com/plataformatec/devise/wiki/How-To:-Add-an-Admin-role

2
  • hi ply, yes User table has column is_admin which is boolean. I tried to "current_user.is_admin" but it is denying instance of current_user. Apr 4, 2013 at 19:30
  • hi ply, user table already has is_admin column and i have used in on other page like <% @users.each do |user| %> <tr class=""> <% if !user.is_admin %> <td><%= user.email %></td> <td><%= user.created_at %></td> <td><%= user. sign_in_count %></td> <td> </td> <% end %> </tr> Apr 4, 2013 at 19:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.