使用mongoid

时间:2015-08-16 00:05:47

标签: ruby-on-rails-4 mongoid

如果保存失败,使用postgreSQL,我们可以返回false value

但与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(#<User::TravelOrganizerController>)> rtn  = @plan.save!
      MOPED: 52.9.119.51:27017 INSERT       database=lazy_bird collection=plans documents=[{"_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 UTC, "session"=>"all_day", "price"=>999.0, "user_id"=>BSON::ObjectId('55c61b64506f631cd2000000'), "updated_at"=>2015-08-15 23:58:01 UTC, "created_at"=>2015-08-15 23:58:01 UTC}] flags=[]
                                COMMAND      database=lazy_bird command={:getlasterror=>1, :w=>1} runtime: 52.3300ms
    Moped::Errors::OperationFailure: The operation: #<Moped::Protocol::Command
      @length=73
      @request_id=36
      @response_to=0
      @op_code=2004
      @flags=[]
      @full_collection_name="lazy_bird.$cmd"
      @skip=0
      @limit=-1
      @selector={:getlasterror=>1, :w=>1}
      @fields=nil>
    failed with error 11000: "E11000 duplicate key error collection: lazy_bird.plans index: user_id_1_from_1_to_1_start_date_1_end_date_1 dup key: { : ObjectId('55c61b64506f631cd2000000'), : \"TAIPEI\", : \"TOKYO\", : new Date(1447632000000), : new Date(1448064000000) }"

    See https://github.com/mongodb/mongo/blob/master/docs/errors.md
    for details about this error.
    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:in `block in execute'

    [8] pry(#<User::TravelOrganizerController>)> rtn
    nil

1 个答案:

答案 0 :(得分:0)

OperationFalire是操作的直接结果,例如插入失败或命令无效。

抓住Exception

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