Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create password and confirmation when using form_for?

I am using form_for, but I'm not sure how to create the password and password confirmation using the helpers?

I have so far:

<%= form_for :user, @user, ....   do |f| %>

<%= f.text_field :user_name, :class ....  %>

password??

<% end %>

Also, when posting to the /user/create action, how to do I prevent certain fields in the model from being initialized when using:

@user = User.new(params[:user])
like image 650
Blankman Avatar asked Oct 25 '10 03:10

Blankman


2 Answers

Put this in your view form:

<%= f.password_field :password %>
<%= f.password_field :password_confirmation %>

And this in your user model:

validates_confirmation_of :password

Now, to prevent unwanted initializations in your controller, add the following to your model:

attr_accessible :attribute1, attribute2

Now these attributes will be the only attributes that can be set through what is called "mass assignment".

like image 152
Jaime Bellmyer Avatar answered Oct 27 '22 04:10

Jaime Bellmyer


If you have a database column password (of course you would better store a salt and encrypted password), then you could do this:

class User
  attr_accessor :password_confirmation # Note. You do not need this field in database, it's for 1-time use

  # The following 2 lines let you prevent certain fields
  attr_accessible :user_name
  attr_protected :password
  # Note that if you used attr_accessible, and all other fields cannot be assigned through User.new(params[:user[), while if you used attr_protected, only those fields cannot assigned.

 validates_confirmation_of :password # This automatically validates if :password == :password_confirmation

In your view:

<%= f.password_field :password %>
<%= f.password_field :password_confirmation %>
like image 41
PeterWong Avatar answered Oct 27 '22 02:10

PeterWong