【问题标题】:Rails 5 + Mongoid virtual attributeRails 5 + Mongoid 虚拟属性
【发布时间】:2017-06-02 11:45:07
【问题描述】:

我正在尝试使用 Rails 5 和 Mongoid 创建一个简单的用户注册功能。我的用户模型和控制器如下所示:

用户.rb

class User
  include Mongoid::Document
  include Mongoid::Timestamps

  validates_presence_of :email
  validates_uniqueness_of :email, case_sensitive: false

  validates :password, presence: true, confirmation: true
  validates_presence_of :password_confirmation

  field :email, type: String
  field :password, type: String
  ...
end

users_controller.rb

...
def create
  @user = User.new(user_params)
  if @user.save
    json_response(nil, nil, :created)
  else
    json_response(@user.errors.full_messages, nil, :bad_request)
  end
end
...
private
  def user_params
    params.require(:user).permit(:email, :password, :password_confirmation, :avatar)
  end

现在我需要检查password_confirmation是否和password一样,两个参数都是通过request发送的,但是password_confirmation没有传递给新的用户对象,虽然它在强参数中被列入白名单:

日志:

Started POST "/users" for 127.0.0.1 at 2017-06-02 13:03:10 +0200
Processing by UsersController#create as JSON
Parameters: {"password"=>"[FILTERED]", email"=>"test@mail.com", "password_confirmation"=>"[FILTERED]", "user"=>{"email"=>"test@mail.com", "password"=>"[FILTERED]"}}

我不想添加

field :password_confirmation

到我的模型,它解决了这个问题。我只需要将属性设为虚拟并在验证后将其删除。我错过了什么或做错了什么?或者说正确的态度是什么?

【问题讨论】:

    标签: ruby-on-rails mongoid ruby-on-rails-5 mongoid6


    【解决方案1】:

    在您的模型中,将其添加为 attr_acessor

    Class User
    ...
    field :email, type: String
    field :password, type: String
    attr_accessor :password_confirmation
    ...
    end
    

    您将能够访问它,但它不会被持久化。

    【讨论】:

    • 不幸的是,这并没有帮助,似乎params.require(:user).permit(...) 只能使用field 定义的那些属性,它忽略了attr_accessor
    • 好吧,作为最后的手段,您可以将它添加为一个字段,但通过创建一个 before_save 过滤器来将其设为 nil 以防止它保存。这很丑,但会起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 2012-07-13
    相关资源
    最近更新 更多