Reputation: 429
I tried looking for an answer but they were all using User.new etc and not create.
When using User.create() in console with valid attributes I'm getting a User created with nil for ID and nil for the timestamps.
Here is my user Model.
class User < ApplicationRecord
attr_writer :name, :email
before_save {self.email = email.downcase}
validates :username, presence:true,
length: {maximum: 30},
uniqueness:true
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence:true,
length: {maximum:200},
format: {with: VALID_EMAIL_REGEX},
uniqueness: {case_sensitive: false}
has_secure_password
validates :password, presence: true,
length: {minimum:6}
end
In the rails console I'm using
User.create(username:"oiuedhioj", email:"[email protected]",password:"test",password_confirmation:"test")
And getting back
<User id: nil, username: "Damhan", email: nil, created_at: nil, updated_at: nil, password_digest: "$2a$10$oGtRgcHigaHh/UCVX4QdM.AOgyGur8Oud5MyKZheUcQ...">
Upvotes: 3
Views: 2511
Reputation: 8345
In addition to the tips you already got, use create!
and save!
etc. instead of their complements to get an exception on error, and thus fail-fast and hence easier to debug code. Only use the variants without !
if you have a good reason. As you have to manually check for errors anyway, having proper exceptions is usually much more cleaner.
Upvotes: 1
Reputation: 3568
Try doing the creation in the rails console.
Returning a record without an Id or timestamps is a sign of an invalid record.
user = User.create(...)
user.valid?
=> false
user.errors.any?
=> true
Upvotes: 6
Reputation: 6564
You've set only name
and email
as writable. Include id
and other properties on that list. Or if your rails version is 4+, use strong parameters in your controller.
#user_controller.rb
...
private
def user_params
params.require(:user).permit(:id, :name, :email ... )
end
...
Upvotes: 1