【问题标题】:ActiveModel::ForbiddenAttributesError Ruby On RailsActiveModel::ForbiddenAttributesError Ruby On Rails
【发布时间】:2014-04-30 01:18:55
【问题描述】:

我在 Ruby On rails 中创建了一个项目,并且我有这样的控制器用户:

class UsersController < ApplicationController
    before_action :set_user, only: [:edit, :update]
    def new
        @user = User.new
    end

    def create
        @user = User.new(params[:user])
        if @user.save
            redirect_to root_url, :notice => "Signed up!"
        else
        render "new"
        end
    end

    private
     def user_params
      params.require(:user).permit(:email, :password, :password_confirmation)
    end
end

像这样模拟用户:

class User < ActiveRecord::Base
  #attr_accessible :email, :password, :password_confirmation

  attr_accessor :password
  before_save :encrypt_password

  def self.authenticate(email, password)
    user = find_by_email(email)
    if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
      user
    else
      nil
    end
  end

  def encrypt_password
    if password.present?
      self.password_salt = BCrypt::Engine.generate_salt
      self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
    end
  end
end

当我尝试创建新用户时出现错误:ActiveModel::ForbiddenAttributesError

参数:

{"utf8"=>"✓",
 "authenticity_token"=>"74Mhbpn9FF/tY/cgfuVmX7ribN4rOkkdUjSgbLNsces=",
 "user"=>{"email"=>"henio180@interia.pl",
 "password"=>"[FILTERED]",
 "password_confirmation"=>"[FILTERED]"},
 "button"=>""}

我正在使用 Ruby on Rails 4.0.3。

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-4 strong-parameters


【解决方案1】:

在您的create 方法更改中:

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

@user = User.new(user_params)

虽然您正确地创建了设置强参数的方法,但您实际上并没有使用它。 Rails 指南中有关于使用强参数的详细信息:http://guides.rubyonrails.org/action_controller_overview.html#strong-parameters

【讨论】:

    猜你喜欢
    • 2013-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    相关资源
    最近更新 更多