Ruby on rails 4 如何使用mongoid处理保存失败
使用postgreSQL,如果保存失败,我们可以返回Ruby on rails 4 如何使用mongoid处理保存失败,ruby-on-rails-4,mongoid,Ruby On Rails 4,Mongoid,使用postgreSQL,如果保存失败,我们可以返回false值 但mongoid有不同之处 您可以看到我试图保存一条新记录,但得到了Moped::Errors::OperationFailure 但是我不能对这个条件流进行错误处理,它永远不会进入else条件 if @plan.save flash[:info] = t('created_a_watch_list_successfully', scope: 'user_section') else flash[:aler
false值
但mongoid有不同之处
您可以看到我试图保存一条新记录,但得到了Moped::Errors::OperationFailure
但是我不能对这个条件流进行错误处理,它永远不会进入else
条件
if @plan.save
flash[:info] = t('created_a_watch_list_successfully', scope: 'user_section')
else
flash[:alert] = t('plan_has_existing', scope: 'user_section')
end
安慰
7]pry(#)>rtn=@plan.save!
MOPED:52.9.119.51:27017 INSERT database=lazy_bird collection=plans documents=[{“\u id”=>BSON::ObjectId('55cfd201506f63131f060000'),“is_enable”=>true,“from”=>“TAIPEI”,“to”=>“TOKYO”,“start_date”=>2015-11-16 00:00:00 UTC,“end_date”=>2015-11-21 00:00:00:00 UTC,“session”=>“all"”=>全天”,“price”=>999.0,“user"id”=>BSON::ObjectId”=>('55c61b64506f631cd2000000'),“在”=>2015-08-15 23:58:01 UTC更新”,在“=>2015-08-15 23:58:01 UTC}”创建]标志=[]
命令数据库=lazy_bird命令={:getlasterror=>1,:w=>1}运行时:52.3300ms
Moped::Errors::OperationFailure:操作:#1,:w=>1}
@字段=零>
失败,错误为11000:“E11000重复密钥错误集合:lazy\u bird.plans索引:用户id\u 1\u from\u 1\u start\u date\u 1\u end\u date\u 1 dup密钥:{:ObjectId('55c61b64506f631cd2000000'),:“TAIPEI\,:“TOKYO\,:新日期(1447632000000),:新日期(1448064000000)}”
看见https://github.com/mongodb/mongo/blob/master/docs/errors.md
有关此错误的详细信息。
from/Users/hsu wei cheng/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/moped-2.0.4/lib/moped/operation/read.rb:50:“执行中的块”
[8] 撬动(#)>rtn
无
是操作的直接结果,例如插入失败或命令无效
只需捕获异常
begin
# success
@plan.save
flash[:info] = t('created_a_watch_list_successfully', scope: 'user_section')
rescue OperationFailure => e
# failed to validate the new Document
flash[:alert] = t('plan_has_existing', scope: 'user_section')
rescue
# some other error occurred, this rescue is optional
end
begin
# success
@plan.save
flash[:info] = t('created_a_watch_list_successfully', scope: 'user_section')
rescue OperationFailure => e
# failed to validate the new Document
flash[:alert] = t('plan_has_existing', scope: 'user_section')
rescue
# some other error occurred, this rescue is optional
end