由于名称验证,无法更新记录

时间:2016-10-12 13:18:34

标签: ruby-on-rails

namespace :send_query do    
    task :to_admins => :environment do 
        contacts = Contact.select(:name, :mobile, :company, :requirement).where(email_sent: false).distinct
        if !contacts.blank?
            contacts.each do |contact|
                GuestMailer.query_email(contact.name,
          contact.mobile,
          contact.company,
          contact.requirement).deliver
          contact.update!(email_sent: true)
            end 
        end
        puts "done sending query emails"
    end
end

我写了一个rake任务来发送电子邮件。发送电子邮件后,我将字段email_sent更新为true。但该事务在发送电子邮件后回滚。

(0.2ms)  BEGIN
  Contact Exists (0.7ms)  SELECT  1 AS one FROM "contacts" WHERE "contacts"."name" = $1 AND ("contacts"."id" IS NOT NULL) AND "contacts"."mobile" = $2 AND "contacts"."requirement" = $3 AND "contacts"."company" = $4 LIMIT $5  [["name", "vamsi pavan mahesh"], ["mobile", "9247474925"], ["requirement", "yo yo honey singhu"], ["company", "mahesh@bla.com"], ["LIMIT", 1]]
   (0.2ms)  ROLLBACK
rake aborted!
ActiveRecord::RecordInvalid: Validation failed: Name has already been taken

以下是联系模式

# == Schema Information
#
# Table name: contacts
#
#  id          :integer          not null, primary key
#  name        :string
#  mobile      :string
#  company     :string
#  requirement :text
#  created_at  :datetime         not null
#  updated_at  :datetime         not null
#  email_sent  :boolean          default(FALSE)
#

class Contact < ApplicationRecord
    validates :name, presence: true 
    validates :mobile, presence: true
    validates :requirement, presence: true
    validates_uniqueness_of :name, scope: [:mobile, :requirement, :company]
end

1 个答案:

答案 0 :(得分:0)

Contact模型上,您可以执行on: :create,这只会在创建操作上应用该验证。

<击> validates :name, presence: true, on: :create

编辑:

正如Mr.Yoshiji先生在评论中所指出的,这是导致验证错误的名称uniqueness验证,因此修复实际上是:

validates :name, uniqueness: { scope: [:mobile, :requirement, :company] }, on: :create