I have a Rails 3.2.2 application using Ruby version 1.9.2. I have created basic authentication for my users by following the tutorial on Railscasts.
I don’t need anything complicated, such as remember me or password resets and I would like to have a good understanding with what’s actually going on before I look into using Devise or anything similar.
At the moment I have user accounts and I can check if the user is logged in by using
<% if current_user %>
So I would like to be able to do
<% if current_user.admin? %>
If I use the above admin? check I get the following error:
undefined method `admin?'
My understanding was that the above checks if the admin is true for the current user. I’ve added an admin column to my user table that’s boolean and set to default = false.
create_table :users do |t|
t.string :name
t.string :initials
t.string :email
t.string :password_digest
t.boolean :admin, :default => false
I have also added the admin column to my seed file so I can have a test admin account
User.create(name: 'Danny', initials: 'DAN', email: 'danny@railsapplication.co.uk', password: 'secret', admin: 'true')
As I have added an admin user, and I’m checking for the boolean value to be true I thought that would be all I needed to do.
Am I missing something?
If you’ve tried to add an
admincolumn to your table by editing the original migration, you’ll have to runrake db:rollbackto drop theuserstable, and thenrake db:migrateto bring the table back with theadmincolumn in place.You can’t edit migrations this way and expect the results to appear in the database automatically. If you want to add columns to a table, you need to generate a second migration:
And then use the
add_columnhelper: