I am trying to use Devise on my User model but when I go into rails console and try User.new I only get:
irb(main):002:0> User.new
=> #<User id: nil, first_name: nil, last_name: nil, email: nil, created_at: nil, updated_at: nil>
Why are the devise columns not showing up?
CreateUsers migration:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :first_name
t.string :last_name
t.string :email
t.timestamps null: false
end
end
end
AddDeviseToUsers migration:
class AddDeviseToUsers < ActiveRecord::Migration
def self.up
change_table :users do |t|
## Database authenticatable
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
# Uncomment below if timestamps were not included in your original model.
# t.timestamps null: false
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
# add_index :users, :confirmation_token, unique: true
# add_index :users, :unlock_token, unique: true
end
def self.down
# By default, we don't want to make any assumption about how to roll back a migration when your
# model already existed. Please edit below which fields you would like to remove in this migration.
raise ActiveRecord::IrreversibleMigration
end
end
Schema shows the columns are there:
create_table "users", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
Any ideas?
It's a security feature that Devise has in order to restrict its attributes and the critical information it contains to be exposed to API calls.
You can however override this, you need to override serializable_hash method.
# app/models/user.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :recoverable, :confirmable, :rememberable, :validatable
...
protected
def serializable_hash(options = nil)
super(options).merge(encrypted_password: encrypted_password, reset_password_token: reset_password_token) # you can keep adding attributes here that you wish to expose
end
end
You can check http://www.rubydoc.info/github/plataformatec/devise/Devise/Models/Authenticatable where a constant is declared to blacklist attributes
BLACKLIST_FOR_SERIALIZATION =[:encrypted_password, :reset_password_token, :reset_password_sent_at, :remember_created_at, :sign_in_count, :current_sign_in_at, :last_sign_in_at, :current_sign_in_ip, :last_sign_in_ip, :password_salt, :confirmation_token, :confirmed_at, :confirmation_sent_at, :remember_token, :unconfirmed_email, :failed_attempts, :unlock_token, :locked_at]
Hope this answers your question!
If all you want to do it list all the attributes in the Rails console, it is easier to use User.first.serializable_hash(force_except: true)
See http://www.rubydoc.info/github/plataformatec/devise/Devise%2FModels%2FAuthenticatable:serializable_hash
Devise overrides the inspect method to not expose internal attibutes. You can try:
User.new.attributes
or
User.new.encrypted_password
(or whatever attribute you want)
You can check inspect method here
Related
I have rails (6.0.2.2) project with devise (4.7.1), with two types of accounts: the teachers and the students. The student can to sign up successfully, but there is problem with the teacher for some reason. When I try to make a test account, I get
Unpermitted parameter: :email
error message and my info is not saved in the database.
Migration:
class DeviseCreateTeachers < ActiveRecord::Migration[6.0]
def change
create_table :teachers do |t|
## Database authenticatable
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
t.string :username
t.string :name
t.string :neighborhood
t.integer :pet_skin
t.integer :pet_eyes
t.integer :pet_face
t.integer :pet_accessories
## Trackable
# t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
t.string :confirmation_token
t.datetime :confirmed_at
t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
t.string :unlock_token # Only if unlock strategy is :email or :both
t.datetime :locked_at
t.timestamps null: false
end
add_index :teachers, :email, unique: true
add_index :teachers, :reset_password_token, unique: true
# add_index :teachers, :confirmation_token, unique: true
# add_index :teachers, :unlock_token, unique: true
end
end
my teacher_controller.rb:
class TeacherController < ApplicationController
private
def sign_up_params
params.require(:teacher).permit(:email, :username, :name, :password, :password_confirmation, :neighborhood, :pet_skin, :pet_eyes, :pet_face)
end
def account_update_params
params.require(:teacher).permit(:username, :password, :password_confirmation, :current_password)
end
end
I'm using the default generated teachers/registration/new.html.erb so I think its no problem here.
I DID add a line to config/initializers/devise.rb:
config.authentication_keys = [:username]
to change default log in from email to username, but I don't think this is issue because again students can create the account.
Thanks for your help!
#Tijana I don't know if you have already checked this.
link. If not, it might help
https://github.com/heartcombo/devise#strong-parameters
I am implementing an authentication system with devise in rails, but when registering the user, in this case a student, the following error is skipped:
ActiveRecord::NotNullViolation in Devise::RegistrationsController#create
SQLite3::ConstraintException: NOT NULL constraint failed: students.codigo: INSERT INTO "students" ("email", "encrypted_password", "created_at", "updated_at") VALUES (?, ?, ?, ?)
I have been solving this error all day, but nothing that I can solve. I have implemented a before_action in the students_controller controller:
class StudentsController < ApplicationController
before_action :configure_devise_params, if: :devise_controller?
def configure_devise_params
devise_parameter_sanitizer.permit(:sign_up) do |user|
user.permit(:codigo, :documento, :nombres, :apellidos, :es_egresado, :email, :password, :password_confirmation)
end
end
...
end
but still the problem is not solved.
The same error happens when I uninstall devise, remove all reference from it, and also, implement strong params in the controller, without this the registry works satisfactorily. But with strong params and devise does not work, it passes data to null in the SQL command.
The student database is the following:
create_table "students", id: false, force: :cascade do |t|
t.integer "codigo", null: false
t.integer "documento", null: false
t.string "nombres", null: false
t.string "apellidos", null: false
t.integer "es_egresado", null: false
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.decimal "promedio_carrera"
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["documento"], name: "index_students_on_documento", unique: true
t.index ["email"], name: "index_students_on_email", unique: true
t.index ["reset_password_token"], name: "index_students_on_reset_password_token", unique: true
end
And its implementation migrate is the following:
class DeviseCreateStudents < ActiveRecord::Migration[5.1]
def change
create_table :students, {
:id => false,
:primary_key => :codigo
} do |t|
## Database authenticatable
t.integer :codigo, null: false
t.integer :documento, null: false
t.string :nombres, null: false
t.string :apellidos, null: false
t.integer :es_egresado, null: false
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
t.decimal :promedio_carrera, null: true
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
# t.integer :sign_in_count, default: 0, null: false
# t.datetime :current_sign_in_at
# t.datetime :last_sign_in_at
# t.string :current_sign_in_ip
# t.string :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
t.timestamps null: false
end
add_index :students, :email, unique: true
add_index :students, :reset_password_token, unique: true
add_index :students, :documento, unique: true
# add_index :students, :confirmation_token, unique: true
# add_index :students, :unlock_token, unique: true
end
end
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"6zdENP1iREYYM+qpqtskqRJ+aB38NIX/nG9jFsoGlImqUVyS9bsmBF6Uc7xvDD/J50/zamlZbbm2rwAaCgOmuw==",
"student"=>
{"codigo"=>"625762",
"documento"=>"107526792",
"nombres"=>"Carlos",
"apellidos"=>"Garnica",
"es_egresado"=>"0",
"email"=>"wcarlosfg.1234567890#hotmail.com",
"password"=>"[FILTERED]",
"password_confirmation"=>"[FILTERED]"},
"commit"=>"Registrar"}
I also clarify that when I create another Student table, removed the previous one, and I remove the null option to the fields, the error does not appear, but the fields that supposedly have been saved remain in NULL in the database
UPDATE: Modify the database, making all fields null, and the form sends null fields whether they have data in the form or not, it is very rare. When doing inspect on the object, it shows the following:
irb(main):002:0> Student.last
Student Load (0.0ms) SELECT "students".* FROM "students" ORDER BY "students"."id" DESC LIMIT ? [["LIMIT", 1]]
=> #<Student id: 2, codigo: nil, documento: nil, nombres: nil, apellidos: nil, es_egresado: nil, promedio_carrera: nil, email: "wcarlosfg.1234567890#hotmail.com", created_at: "2018-09-30 07:46:39", updated_at: "2018-09-30 07:46:39">
SOLUTION: After a day looking at the error, the only solution was to overwrite the devise driver for records, with this, I was able to add the logic and implement strong params to make the registry work correctly.
I keep getting this error when I try to run my application. It states that there is an undefined method error in the application, but doesn't state where. The closest error I could find as tangible was this:
NameError (undefined local variable or method `confirmed_at' for #<User:0x6049800>):
I'm not sure which part this is directing to. Could someone please tell me what this error means?
This is the code for the devise_users file
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
## Database authenticatable
t.string :name, null: false, default: ""
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
t.string :about
t.string :avatar
t.string :cover
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
t.string :confirmation_token
t.datetime :confirmed_at
t.datetime :confirmation_sent_at
t.timestamps null: false
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
t.timestamps null: false
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
add_index :users, :confirmation_token, unique: true
# add_index :users, :confirmation_token, unique: true
add_index :users, :unlock_token, unique: true
end
end
There are not any other places within the application where the method is called, therefore the error states that the method is being called somewhere when it isn't. How can I fix this error?
Your migration file DeviseCreateUsers created a table users in the database, and one of the columns in that table is confirmed_at.
In your app/models/user.rb file you probably declared your devise configuration like:
class User < ActiveRecord::Base
devise :registerable, :confirmable
...
end
ActiveRecord::Base, the class User is inheriting from, automatically creates "getter" and "setter" methods for database columns (i.e. confirmed_at), so the method #confirmed_at should already be defined.
So if the method is "missing", you may not have run the database migrations (e.g. rake db:migrate)
Search your code for confirmed_at -- it seems you used it somewhere without defining it first.
It would be nice if the error message gave you a file name and a line number, but (depending on which text editor or IDE you're using) you might be able to run a search on the entire Rails app at once.
My guess is you called the confirmed_at method on a user object (user_1.confirmed_at, for example) and the method wasn't defined in class User.
Learning rails, using the treehouse videos to build a simple social network.
After making the following changes to add additional fields to devise:
new.html.erb (New Registration)
<div><%= f.label :username %><br>
<%= f.text_field :username %></div>
devise_create_users migration file
t.string :username,
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
I use rake db:reset and then rake db:migrate to attempt to initiate the database changes however the schema remains the same, without the username field.
I get the error: undefined method `username' for #
On the line:
<%= f.text_field :username %></div>
Any help really appreciated, not sure if this is a version related issue or whether treehouse has left out some information.
Thanks!
Devise Migration:
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
## Database authenticatable
t.string :username,
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
t.timestamps
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
# add_index :users, :confirmation_token, unique: true
# add_index :users, :unlock_token, unique: true
end
end
schema:
# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20140720141519) do
create_table "articles", force: true do |t|
t.string "name"
t.string "title"
t.text "content"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "comments", force: true do |t|
t.string "name"
t.text "body"
t.integer "article_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "comments", ["article_id"], name: "index_comments_on_article_id"
create_table "users", force: true do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
You have a typo in your migration. Comma is not needed at the end of line
t.string :username,
As I see there is no username column in users table in your schema. Just remove the comma and recreate you database with $ rake db:drop && rake db:create && rake db:migrate.
I'm absolutely new to Rails, I nearly do not know what I am doing. But. The problem is: signing up new user with Devise results in:
SQLite3::ConstraintException: column email is not unique:
INSERT INTO "users" ("created_at","encrypted_password", "name", "updated_at")
VALUES (?, ?, ?, ?)
And the request parameters:
{"utf8"=>"✓",
"authenticity_token"=>"1bgk4ovS3JitphVkIvcCZi3ex8QsBq4eEf6ZihQLiHg=",
"user"=>{"name"=>"Someone",
"email"=>"8#prosto.me",
"password"=>"[FILTERED]"},
"commit"=>"Sign up"}
User model:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable;
end
DB migration:
class DeviseCreateUsers < ActiveRecord::Migration
def self.up
change_table(:users) do |t|
## Database authenticatable
t.string :email, :null => false, :default => ""
t.string :name, :null => false, :default => ""
t.string :encrypted_password, :null => false, :default => ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, :default => 0
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, :default => 0 # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
## Token authenticatable
# t.string :authentication_token
# Uncomment below if timestamps were not included in your original model.
# t.timestamps
end
add_index :users, :email, :unique => true
add_index :users, :name, :unique => true
add_index :users, :reset_password_token, :unique => true
# add_index :users, :confirmation_token, :unique => true
# add_index :users, :unlock_token, :unique => true
# add_index :users, :authentication_token, :unique => true
end
def self.down
# By default, we don't want to make any assumption about how to roll back a migration when your
# model already existed. Please edit below which fields you would like to remove in this migration.
end
end
Please tell me if I need to provide any other code.
And thank you for all your help in advance.
Update with DB schema:
ActiveRecord::Schema.define(version: 20131012114812) do
create_table "users", force: true do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
t.string "name"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
Update 2: And there is also a problem with authentication. Devise tells 'Invalid email or password' for any previously successfully signed up user in attempt to login.
SQLite is telling you that it's trying to create a new record, where one of the values will be an email, but there is already an existing record with that email.
An easy way to read your database records is query the DB in a terminal window:
$ rails console
$ User.all
If you want to see your test DB, which will be loaded with your fixtures:
$ rails console -e=test
$ User.all
Look for records that have the same email of the one you're trying to create.
If this is your first time using Devise, you should check your fixtures. Devise currently defaults to two fixtures that have no attributes. If you're running in a test environment then those fixtures will be loaded into the test DB as a two records with nil values for email, which are duplicate email values. Fixtures like the ones below will get you passed your error message.
file: app/test/fixtures/users.yml
one:
email: user#example.com
encrypted_password: password1
two:
email: user2#example.com
encrypted_password: password2
Do you have any other "email" columns in that database?
Perhaps you already had a "users" table, where the email column has been replicated with Devise. It would be helpful if you could show us which columns your table has :)
Try adding a uniqueness validation to your User model:
validates_uniqueness_of :email, :allow_blank => true
This will re-render your user creation form instead of causing an error.