使用form_for时如何创建密码和确认?

时间:2010-10-25 03:15:50

标签: ruby-on-rails forms

我正在使用form_for,但我不确定如何使用帮助程序创建密码和密码确认?

我到目前为止:

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

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

password??

<% end %>

此外,在发布到/ user / create操作时,如何在使用时阻止模型中的某些字段被初始化:

@user = User.new(params[:user])

2 个答案:

答案 0 :(得分:16)

将它放在您的视图表单中:

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

这在您的用户模型中:

validates_confirmation_of :password

现在,为了防止控制器中出现不需要的初始化,请将以下内容添加到模型中:

attr_accessible :attribute1, attribute2

现在,这些属性将是唯一可以通过所谓的“质量分配”设置的属性。

答案 1 :(得分:2)

如果你有一个数据库列password(当然你最好存储一个盐和加密密码),那么你可以这样做:

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

在您看来:

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