铁路确认

时间:2017-09-07 12:22:35

标签: ruby-on-rails

我最近在轨道指南之后制定了确认规则,如下:

  validates :email, email: true, uniqueness: true, confirmation: true
  validates :email_confirmation, presence: true

一切都很酷,但是当我尝试更新现有记录时,我收到错误:

irb(main):004:0> User.first.update_attributes!(name: "Some Nameee")
  User Load (2.9ms)  SELECT  "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ?  [["LIMIT", 1]]
   (0.4ms)  begin transaction
  User Exists (0.8ms)  SELECT  1 AS one FROM "users" WHERE "users"."email" = ? AND ("users"."id" != ?) LIMIT ?  [["email", "email@mail.com"], ["id", 1], ["LIMIT", 1]]
   (0.3ms)  rollback transaction
ActiveRecord::RecordInvalid: Validation failed: Email confirmation can't be blank
    from (irb):4

这很明显,因为presence: true字段上有:email_confirmation。如果我将它删除,你可以跳过该fild,只是不要通过它。

那么,我该怎么办?只需删除:presence验证?

2 个答案:

答案 0 :(得分:3)

为什么不检查电子邮件是否已更改的条件验证? http://guides.rubyonrails.org/active_record_validations.html#using-a-symbol-with-if-and-unless

$ bin/rails my_custom_gem:install:migrations

以下是检查模型实例是否已更改的文档:http://api.rubyonrails.org/classes/ActiveModel/Dirty.html

答案 1 :(得分:0)

我通过在验证规则

上明确定义:on => :create来解决这个问题
validates :email_confirmation, presence: true, :on => :create

可以这样使用它吗?我问,因为http://guides.rubyonrails.org/没有提到这一点,所以可能是一个糟糕的决定。