Add custom column to User Model using rails Clearance gem
-
25-05-2021 - |
Question
I use the Clearance gem to add authentification to my website. The standard User model looks like this:
class User < ActiveRecord::Base
include Clearance::User
end
Now i want to add more properties to the User Model. I created this migration:
class AddCustomernameToUsers < ActiveRecord::Migration
def change
add_column :users, :customername, :string
end
end
After rake db:migrate, the database now has one more column for :customername
as next step I edited the User Model file so it looks like this:
class User < ActiveRecord::Base
include Clearance::User
attr_accessor :customername
end
As the next step, I signed up a new user and used sqlite database browser to add the test string 'charly' in the customer name field for this user.
In my controller, i now want to create a user object and print it out to see if all the data is present.
thisUser = User.find(current_user.id)
puts thisUser.inspect
the console output is:
#<User id: 1, email: "test@test.de", encrypted_password: "0494a9b3b692acaea96ab57bed500adf26dbafa5", salt: "75c889d099438476204ce46b9cb406fb1f73423c", confirmation_token: nil, remember_token: "907b9bd600246d0b8dcc06a782457665f614b368", created_at: "2012-03-21 20:59:44", updated_at: "2012-03-21 21:12:59", customername: nil>
so customername is nil. somehow the data for this field is not pulled out of the database correctly.
what am i doing wrong?
Sorry, I'm a rails beginner. Might be a very simple thing to do, but I tried hard and googled all day and couldn't get it to work, so I turn to the wisdom of stack overflow. Thanks guys.
La solution
Instead of using attr_accessor in User model, use attr_accesible :customername and it will work. Because without attr_accessible, data will not be saved in your database and that is the reason you are getting nil value for the field.
Autres conseils
Are you sure you are editing the correct database when using the sqlite database browser? If so I would try modifying your user creation code to include the customer name rather than adding it using a separate tool and seeing if that helps.