Topic: Bypass password validations if current user is admin

Okay let's say the current_user is an admin and they're doing something with somebody's profile. Currently they would have to type in that users password, to get anything to submit.

Instead I would like an admin to be able to edit anyones info without the need to type their password.

PS: This is so that an admin can goto someone's profile and make them an admin.

I tried this

# app/models/user.rb
  ...
  validations :password, presence: true, unless: Proc.new { |user| user.admin? }

But instead of checking if the current user is an admin, it checks the user being edited.

Re: Bypass password validations if current user is admin

Try this:

validations :password, :presence => true, :unless => current_user.admin?

Last edited by wesf90 (2012-02-25 22:08:58)

Remember to edit your topic title and add "[SOLVED]" if your question has been answered!

Follow me!

Re: Bypass password validations if current user is admin

That syntax is the 1.9 syntax.

Also that's bad practice to include current_user inside a model.. I need a better cleaner way.

I wonder if I could use `attr_accessor :current` then somehow call that from a controller to use for the unless in the validation.

Re: Bypass password validations if current user is admin

Also that doesn't work. I get a `undefined local variable or method `current_user' for ...` error

Re: Bypass password validations if current user is admin

Okay so I figured it out.

First I had to edit the model

#user.rb - Model
cattr_accessible :admin_account

validates :password, unless: admin_account

Now the contorller

# users_controller.rb

# If current_user is an admin make :admin_account the current user
User.admin_account = current_user if current_user != @user && current_user.admin?

We create an attribute called admin_account then require password if admin_account is nil.
In the controller we set the admin_account to current_user if current_user is an admin and they are editing someone else's account.

Last edited by larzconwell (2012-02-26 16:14:40)

Re: Bypass password validations if current user is admin

Hello larzconwell,

Can you please explain a bit more. I have a similar requirement on this.
It would be helpful.
I have an admin. He can see list of users. Beside every user there is a button which will lead to the particular's user's profile.
After finishing the task the admin can return to its own login page.
How can I achieve this?



Thanks,
Avi