当我提交 Rails 5 表单时,为什么我的表单字段被设置为空?

Why are my form fields getting set to empty when I submit my Rails 5 form?

我正在使用Rails 5.我有以下型号

class User < ApplicationRecord

  attr_accessor :username, :email, :password, :password_confirmation

  EMAIL_REGEX = /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/
  validates :username, :presence => true, :uniqueness => true, :length => { :in => 3..20 }
  validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX
  validates :password, :confirmation => true #password_confirmation attr
  validates_length_of :password, :in => 6..20, :on => :create

  before_save :encrypt_password
  after_save :clear_password

  def encrypt_password
    if password.present?
      self.salt = BCrypt::Engine.generate_salt
      self.encrypted_password= BCrypt::Engine.hash_secret(password, salt)
    end
  end
  def clear_password
    self.password = nil
end

end

下面是我在控制器中收到该信息后的保存方式……

  def create
    @user = User.new(params.require(:user).permit(:username, :email, :password, :password_confirmation))
    if @user.save
      flash[:notice] = "You signed up successfully"
      flash[:color]= "valid"
    else
      flash[:notice] = "Form is invalid"
      flash[:color]= "invalid"
    end
    render "new"
  end

但是当我提交我的表单时,虽然你可以从下面的日志中看到“电子邮件”和“用户名”的值,但出于某种原因,当我尝试和处理一些事情时,这些值被清除了……

Started POST "/users" for 127.0.0.1 at 2016-12-06 10:45:39 -0600
  ActiveRecord::SchemaMigration Load (0.3ms)  SELECT "schema_migrations".* FROM "schema_migrations"
Processing by UsersController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"btf3ceTkB51g65p7vl1aFkLS+vKun9Xdl3PPW9fSbcNsJn/4jk8fo1ekis8d4Foc7lzmeEITwfjdkos07ndZ5g==", "user"=>{"username"=>"myemail", "email"=>"myemail@msn.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Signup"}
   (0.2ms)  BEGIN
  User Exists (1.5ms)  SELECT  1 AS one FROM "users" WHERE "users"."username" =  LIMIT   [["username", "myemail"], ["LIMIT", 1]]
  User Exists (0.4ms)  SELECT  1 AS one FROM "users" WHERE "users"."email" =  LIMIT   [["email", "myemail@msn.com"], ["LIMIT", 1]]
  SQL (3.4ms)  INSERT INTO "users" ("encrypted_password", "salt", "created_at", "updated_at") VALUES (, , , ) RETURNING "id"  [["encrypted_password", "a$h6V6zoZOrPmurBWfoAuzwOcOXurYWc6aqLmgL1Z0wD7V1qhfRywRy"], ["salt", "a$h6V6zoZOrPmurBWfoAuzwO"], ["created_at", 2016-12-06 16:45:39 UTC], ["updated_at", 2016-12-06 16:45:39 UTC]]
   (0.2ms)  ROLLBACK
Completed 500 Internal Server Error in 104ms (ActiveRecord: 12.7ms)

如何保留提交的字段值?

尝试删除此行。当然,所有这些字段都存在于 table

attr_accessor :username, :email, :password, :password_confirmation