有人可以帮我解决使用rails version-3.2.19的以下错误吗?当我向数据库提交值时,这个错误即将来临。
错误
ActiveModel::MassAssignmentSecurity::Error in UsersController#create
Can't mass-assign protected attributes: con_password
我的代码段如下。
视图/用户/ new.html.erb
<center>
<h1>Enter your data</h1>
<% if @user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@user.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @user.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-div">
<%= form_for :user,:url => {:action => 'create'} do |f|%>
<p>
<%= f.label :Name %>
<%= f.text_field :name,placeholder:"Enter your name" %>
</p>
<p>
<%= f.label :Email %>
<%= f.email_field :email,placeholder:"Enter your Email" %>
</p>
<p>
<%= f.label :Password %>
<%= f.password_field :password,placeholder:"Enter your password" %>
</p>
<p>
<%= f.label :password %>
<%= f.password_field :con_password,placeholder:"Enter your password again" %>
</p>
<p>
<%= f.label :content %>
<%= f.text_field :content,placeholder:"Enter your content" %>
</p>
<p>
<%= f.submit "Create User",:class => 'submit' %>
</p>
<% end %>
</div>
</center>
控制器/ users_controller.rb
class UsersController < ApplicationController
def index
end
def new
@user=User.new
end
def show
end
def create
@user=User.new(params[:user])
if @user.save
flash[:notice]="User has created successfully"
flash[:color]="valid"
redirect_to :action => 'index'
else
flash[:alert]="User could not create"
flash[:color]="invalid"
render :new
end
end
end
模型/ user.rb
class User < ActiveRecord::Base
attr_accessible :content, :email, :name, :password
EMAIL_REGEX = /\A[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\z/i
validates :name, :presence => true, :uniqueness => true, :length => { :in => 3..20 }
validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX
validates :password, :confirmation => true
validates_length_of :password, :in => 6..20, :on => :create
end
迁移\ 20150128062543_create_users.rb
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email
t.string :password
t.string :content
t.timestamps
end
end
end
请帮我解决这个问题。
答案 0 :(得分:0)
您应该为您的字段<%= f.password_field :con_password,placeholder:"Enter your password again" %>
命名,而不是password_confirmation
,因为如果它具有validates :password, confirmation: true
,那么这就是您的模型所期望的:
<%= f.password_field :password_confirmation, placeholder: "Enter your password again" %>
您还必须在模型中将password_confirmation
添加到attr_accessible
。