3
votes

I'm using Devise to manage users in my rails app. I have a button available to admin users which leads to a form that allows them to create other admin user accounts.

When the form is submitted this code is called:

@user = User.new(:email => params[:email], :password => params[:password], :password_confirmation => params[:password_confirmation])
@user.admin = true
@user.save

It doesn't seem to be working correctly as when I sign out and try to sign in with the new admin account it fails. I'm guessing the above code isn't the correct way to create a new user with Devise.

Edit:

Logs

Started POST "/users/13/create_admin" for 127.0.0.1 at 2013-07-16 17:01:38 +0100
Processing by UsersController#create_admin as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"VpP78Zy8SAcyC1Mgg6hEjG2I5jqNzIHXQGtbjUzDYVE=", "users"=>{"email"=>"[email protected]", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up", "id"=>"13"}
  User Load (0.5ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 13 LIMIT 1
   (0.3ms)  BEGIN
   (0.1ms)  ROLLBACK
  Rendered users/create_admin.html.erb within layouts/application (0.0ms)
Completed 200 OK in 12ms (Views: 5.3ms | ActiveRecord: 0.9ms)

Here's my form:

  <%= form_for :users, :html => { :id => "signup-form" }, :url => create_admin_user_path do |f| %>
<div><%= f.label :email %>
<%= f.email_field :email, :autofocus => true %></div>

<div><%= f.label :password %>
<%= f.password_field :password %></div>

<div><%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation %></div>

<div class="actions">
  <div><%= f.submit "Sign up", :class => "btn btn-success" %></div>
</div>
2
Is the user created in the database? When you attempt to log in with the new account, does it indicate that the password is wrong? Can you run a password reset with the new account's email address?James Chevalier
is your admin really a "User", or is it an "AdminUser" or "Administrator" ?Jesse Wolgamott
Can you please post your User modal?Firoz Ansari
@JamesChevalier I checked the db and it's not being added to the Users table.user470763
change to @user.save! -- you'll get the reason why it's not saving then for sureJesse Wolgamott

2 Answers

2
votes

you're actually posting

"users"=>{"email"=>"[email protected]", "password"=>""}

So, you should be

@user = User.new(:email => params[:users][:email], :password => params[:users][:password], :password_confirmation => params[:users][:password_confirmation]))
@user.admin = true
@user.save
1
votes

In new devise one should remove password from params hash. If password is blank. E.g. we want to edit profile but do not change password. Or devise will fail validation.

if params[:user][:password].blank?
  params[:user].delete(:password)
  params[:user].delete(:password_confirmation)
end

See documentation for more details.