Chris Dormani
Chris Dormani

Reputation: 510

difficulty configuring rails console to identify an admin

I am newish to rails and programming and having a spot of bother in the rails console configuring such to identify myself as a administrator. Immediately after the user.save command is executed my admin value still remains false and I get a console note that says.

Console

0.2ms)  begin transaction
   (0.1ms)  rollback transaction
 => false 

Here is what I have done so far.

_add_admin_to_users.rb

class AddAdminToUsers < ActiveRecord::Migration
  def change
    add_column :users, :admin, :boolean, default: false
  end
end

Rails console admin save process

user = User.find_by(email: '[email protected]')
user.admin = true
user.save
user.admin?

user.rb

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


    has_many :pins, dependent: :destroy   

    validates :name, presence: true  

 def admin?
     admin
 end

end

Upvotes: 0

Views: 65

Answers (2)

Rajarshi Das
Rajarshi Das

Reputation: 12320

You can try this by escaping validation

user = User.find_by(email: '[email protected]')
user.admin = true

Now before rails < 3

user.save(false)
user.admin?

Or after rails 3

user.save(:validate => false)
user.admin?

or if you do not want to escape validation

user = User.find_by(email: '[email protected]')
user.name = "Admin"
user.admin = true
user.save
user.admin?

Upvotes: 0

Thorin
Thorin

Reputation: 2034

There are some validation or something fails in save so all process cancelled, you can see there are text like this:

   (0.1ms)  rollback transaction
 => false 

 It means save process rollback

 Use user.save! to see error and it seems to me error due to validation on name field of user

Try this:

user = User.find_by(email: '[email protected]')
user.name = "Admin"
user.admin = true
user.save
user.admin?

Upvotes: 1

Related Questions