Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Devise: Adding first_name to Users

Rails 3.1
Devise 1.4.2

I've added first_name and last_name columns to devise's User table. Then I've used to console to add a first_name and last_name for my first user.

Now, my application.html.erb displays my first name and last name thanks to the following code after I've made sure the user is logged in:

<%= current_user.first_name %> <%= current_user.last_name %>(<%= current_user.email %>)

Here's my problem: when I try to register a new user via the new user form I've created, the first_name and last_name are not stored in the database or something... because when I log in with the new user the code I have on my application.html.erb does not display the first and last name.

Here's the text fields for the first and last name in the new.html.erb:

<p><%= f.label :first_name %><br />
   <%= f.text_field :first_name %></p>

<p><%= f.label :last_name %><br />
   <%= f.text_field :last_name %></p>

<p><%= f.label :email %><br />
   <%= f.email_field :email %></p>

I'd also like to know how to add validation for these new columns I've created (first_name and last_name).

Thanks in advance!

like image 927
imjp Avatar asked May 11 '26 17:05

imjp


1 Answers

Rails 3

By default, devise makes all attributes protected. For any attribute you want to be able to mass assign (e.g via a form), you need to explicitly allow it in your model:

attr_accessible :first_name, :last_name

It worked in your console because you probably did something like this:

@user = User.first
@user.first_name = "foo"
@user.save

But this won't work if the attribute is not accessible:

@user = User.new(:first_name => "foo")
@user.save

You'll should see a warning "Can't mass assign protected attributes" in your log file.

For validations, check out the Rails docs or this guide. For example, to ensure a full name is provided, add

validates_presence_of :first_name, :last_name

to your model.

like image 67
Thilo Avatar answered May 13 '26 08:05

Thilo