English 中文(简体)
如何在save()过程中捕获ActiveRecord::RecordNotFound异常?
原标题:How to catch ActiveRecord::RecordNotFound exception during save()?

我的数据库中有一个“用户”表和一个“电子邮件”列。我还在电子邮件列上创建了一个UNIQUE索引,以防止两个用户注册相同的电子邮件地址(注意:请不要建议我使用validates_uniqueness_of,因为这是我试图避免的)。

当我运行RSpec测试以确保不能插入重复的记录时,我看到以下错误:

Failures:
  1) User should not allow duplicate email addresses
     Failure/Error: user2.save.should_not be_true
     ActiveRecord::RecordNotUnique:
       SQLite3::ConstraintException: column email is not unique: INSERT INTO "users" ("email", ... ) VALUES ( ... )
     # ./spec/models/user_spec.rb:26

这很好,因为这意味着我的UNIQUE索引确实有效。问题是,我该如何处理此异常?我希望能够捕捉到它,然后向模型的错误集合添加一条合理的消息。

我尝试在控制器中使用rescue_from,但没有成功,如下所示:

rescue_from  ActiveRecord::RecordNotUnique  do |ex|
    raise  Email must be unique 
end

Rails API文档似乎没有建议如何覆盖save()方法来添加开始/救援块,所以我的问题是:如何处理在save()过程中抛出的ActiveRecord::RecordNotUnique异常,然后将模型标记为无效,并向模型的错误集合添加合理的错误消息?

最佳回答
class User
...
def save
 super
 rescue  ActiveRecord::RecordNotUnique  
   logger.error($!.to_s) # or something like that.
 end
end

您可以重载模型中的任何操作,只需调用super即可执行继承的方法定义

Rails API没有提到它,因为它是Ruby的一个特性,而不仅仅是Rails。

问题回答

我也有类似的问题。我有一个表,它有一个索引,使用了表排序的几个字段

在db/migrate

class CreateDids < ActiveRecord::Migration
  def change
    create_table :dids do |t|
      t.string :lada, null: false, limit: 3
      t.string :pre_did, null: false, limit: 4
      t.string :did, null: false, limit: 7
      t.boolean :uso_interno_ns, default: false, null: false

      t.timestamps
      t.integer :lock_version, null: false, default: 0
      t.index [:lada, :pre_did, :did], unique: true
    end
  end
end

现在,为了验证models/did.rb中独特的字段组合,我写道:

  validates :lada, presence: true, length: { within: 1..3 }, numericality: { only_integer: true}
  validates :pre_did, presence: true, length: { within: 1..4 }, numericality: { only_integer: true}
  validates :did, presence: true, length: { within: 4..7 }, numericality: { only_integer: true}
  validate do
    errors.add :base,I18n.t( dids.numero_menor_10 ) unless 10 == ( self.lada + self.pre_did + self.did ).size if self.lada and self.pre_did and self.did
  end

但是,它没有验证字段的重复混合(lada+pre_did+did),因此在models/did中。rb还写道:

def save
  begin
    super
  rescue ActiveRecord::RecordNotUnique => e
    errors.add(:base,I18n.t( dids.telefono_duplicado ))
    false
  end
end

def update( x )
  begin
    super x
  rescue ActiveRecord::RecordNotUnique => e
    errors.add(:base,I18n.t( dids.telefono_duplicado ))
    false
  end
end

现在,在我的情况下,如果我在救援后没有返回false,这是不起作用的。





相关问题
rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

SSL slowness in EC2

We ve deployed our rails app to EC2. In our setup, we have two proxies on small instances behind round-robin DNS. These run nginx load balancers for a dynamically growing and shrinking farm of web ...

Auth-code with A-Za-z0-9 to use in an URL parameter

As part of a web application I need an auth-code to pass as a URL parameter. I am currently using (in Rails) : Digest::SHA1.hexdigest((object_id + rand(255)).to_s) Which provides long strings like : ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

activerecord has_many :through find with one sql call

I have a these 3 models: class User < ActiveRecord::Base has_many :permissions, :dependent => :destroy has_many :roles, :through => :permissions end class Permission < ActiveRecord::...

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

How to get SQL queries for each user where env is production

I’m developing an application dedicated to generate statistical reports, I would like that user after saving their stat report they save sql queries too. To do that I wrote the following module: ...

热门标签