Rails 5 + Mongoid虚拟属性

时间:2017-06-02 11:45:08

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

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

user.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是否与密码相同,两个params都是通过请求发送的,但是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

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

1 个答案:

答案 0 :(得分:0)

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

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

您将能够访问它,但它不会被保留。