【问题标题】:Rails 4 - Switching from protected attributes to strong parametersRails 4 - 从受保护的属性切换到强参数
【发布时间】:2014-03-30 17:49:11
【问题描述】:

我遵循rails cast tutorial 进行用户身份验证/注册/登录,这显然具有使用 gem 保护属性的过时方法。我发现有必要切换到强参数,并通过关注this method 这样做。

我不得不从我的 user.rb 模型中删除 attr_accessible 代码(在下面注释掉),我想知道除了在控制器中定义用户参数之外,我还应该做些什么。既然我没有 attr_accessible 或者这是不必要的,用户字段(电子邮件、密码、位置)是否应该有 attr_accessors?我是 Rails 新手,不完全了解用户身份验证的正确必要性。

user.rb

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

  attr_accessor :password, :location
  before_save :encrypt_password

  validates_confirmation_of :password
  validates_presence_of :password, :on => :create
  validates_presence_of :email
  validates_uniqueness_of :email

  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 

user_controller.rb

class UsersController < ApplicationController
  def new
    @user = User.new
  end

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

  #add thing from https://stackoverflow.com/a/19130224/2739431
  private
    def user_params
      params.require(:user).permit(:email, :password, :password_confirmation, :location)
    end

end

【问题讨论】:

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


    【解决方案1】:

    答案比较简单。

    请记住您刚开始学习 Ruby 时的那句话:“在 Ruby 中,一切都是对象”。对象有方法,要访问对象属性,您需要一个accessor 方法。

    attr_accessor 是一个 Ruby 方法,它为给定的实例变量生成访问器方法(检查 attr_readerattr_writer)。
    所以你的问题实际上是你是否需要在Model之外访问这些属性。

    我认为这回答了你的问题。

    重要提示attr_accessible 不是 Ruby 方法。这是一种 Rails 方法,允许您将值传递给模型以进行批量赋值:new(attrs)update_attributes(attrs)

    【讨论】:

    • “所以你的问题实际上是你是否需要在模型之外访问这些属性。”但是 ActiveRecord 会自动为数据库字段生成访问器,因此“是否需要访问模型之外的那些属性”并不是一个真正的问题,因为访问器已经存在。
    • 你是对的。但是您确实说过数据库字段,它们可能不是字段,而是实例变量。确实有区别,但我试图更通用,这样以后人们就不会混淆这两件事了。
    【解决方案2】:

    用户的字段(电子邮件、密码、 位置)现在我没有 attr_accessible 或者这是 没必要?

    没必要。 ActiveRecord 自动为模型字段创建写入器和读取器——这就是为什么您可以在 User 类之外使用 user.emailuser.email = 等方法。

    attr_accessor :password, :location – 我猜这些是数据库字段,对吧?您也可以删除此行。

    【讨论】:

    • 当我删除该行时,我收到一条错误消息,提示我在尝试注册新用户时找不到参数“密码”。
    • 好的,一切都很好,看起来passwordlocation 操作的是实例变量,而不是数据库字段。
    • 奇怪的是,当我为 :email 添加一个时,一旦我创建它就不会让我登录帐户。我猜是因为它会干扰电子邮件的数据库字段。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    • 2012-12-11
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    相关资源
    最近更新 更多