0
votes

My code:

class TestController < ApplicationController
  def testpage
    user = User.new(:email => '[email protected]', :encrypted_password => 'test')
    user.save
  end
end

I am trying to save a user manually from inside the script, but it never saves, however I am able to update the user by following code:

class TestController < ApplicationController
  def testpage
    user=User.find(2)
    user.update(:email => 'new', :encrypted_password => 'new')
  end
end

So my second code is working fine, but not first, I don't know why. Here is my User model:

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

  belongs_to :manager
end

I have no idea what is wrong, I want to save users. I am using devise. And I am not getting any kind of errors as well.

edit1: On replacing user.save with user.save! I am getting this error.

Validation failed: Password can't be blank, Password confirmation doesn't match Password

2
Try this: User.new(email: '[email protected]', password: 'test', password_confirmation: 'test'). This should work. - Deepesh
@Deep didn't work, any more suggestions? - user1735921
What is the error you are getting? Just replace user.save with user.save! and see what is the error. - Deepesh
Validation failed: Password can't be blank, Password confirmation doesn't match Password I have both passwords as test, but still this error, weird... - user1735921
Try this User.create!(email: '[email protected]', password: 'test', password_confirmation: 'test') - Prashant4224

2 Answers

1
votes

The column encrypted_password where you store a hashed password is usually protected from modification. Instead few accessors provide an interface to setup the password followed by encryption.

So this is what you need:

class TestController < ApplicationController

  def create
    user = User.new
    user.email = 'new'
    user.password = user.password_confirmation = 'new'
    if user.valid?
      user.save
    else
      redirect_to :back
    end
  end


  def update
    user = User.find(2)
    if user
      user.email = 'new'
      user.password = user.password_confirmation = 'new'
      user.save
    end
  end
end

I suppressed errors and exception handling so make sure you cover those cases before deployment.

0
votes

Or you can use

user = User.create(email: '[email protected]', encrypted_password: 'test')

instead of

user = User.new(email:  '[email protected]', encrypted_password:  'test')
user.save