尝试创建用户时获取“ActiveModel :: ForbiddenAttributesError”

时间:2016-12-06 02:22:26

标签: ruby parameters model submit ruby-on-rails-5

我正在使用Rails 5和PostGres 9.5。我在提交用于在我的数据库中创建用户的表单时遇到问题。我在我的控制器中有这个

  def create
    @user = User.new(params[:user])
    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

以下是我的表在PostGres数据库中的显示方式...

sims=> \d users;
                                         Table "public.users"
       Column       |            Type             |                     Modifiers                      
--------------------+-----------------------------+----------------------------------------------------
 id                 | integer                     | not null default nextval('users_id_seq'::regclass)
 username           | character varying           | 
 email              | character varying           | 
 encrypted_password | character varying           | 
 salt               | character varying           | 
 first_name         | character varying           | 
 last_name          | character varying           | 
 created_at         | timestamp without time zone | not null
 updated_at         | timestamp without time zone | not null
Indexes:
    "users_pkey" PRIMARY KEY, btree (id)

但是在提交带有以下参数的表单后,我收到错误,正如您从我的日志中看到的那样......

Processing by UsersController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"q4YmPjUhD5olnRRgCt/gUuCDrb0lt+EqOxpzXGdtGHBtkwPEYgyp12H8lF04FHpqrZRZCip1Mo8/tvGQinPpJg==", "user"=>{"username"=>”mysuername”, "email"=>”mysuername@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Signup"}
Completed 500 Internal Server Error in 1ms (ActiveRecord: 0.0ms)



ActiveModel::ForbiddenAttributesError (ActiveModel::ForbiddenAttributesError):

日志中没有其他信息。我还需要做些什么才能提交表单?

1 个答案:

答案 0 :(得分:2)

由于安全问题,Rails正在阻止保存。本指南有一个简洁明了的解释:http://blog.teamtreehouse.com/rails-4-strong-paremeters

要修复您的具体示例,请将@user = User.new(params[:user])行更改为:

@user = User.new(params.require(:user).permit(:username, :email, :password, :password_confirmation))