【问题标题】:Error handing using create! method in Rails4使用 create! 处理错误! Rails 4 中的方法
【发布时间】:2014-09-05 07:28:10
【问题描述】:

我正在使用 rails4。在我的控制器中,我解析 json 并存储到数据库中。 我的控制器是这样的,

def store
  @data.each do |invite|
     MemberInvitation.create!(:email => invite['email'])
  end
end

这很好用....

我们知道create will automatically call validators 但是如果验证失败如何使用 json 渲染显示错误消息。因为我在 MemberInvitation 模型中定义验证。

如何处理这种情况!!!

如果出现错误,我想以 json 格式呈现错误消息!!!

【问题讨论】:

    标签: ruby-on-rails json ruby-on-rails-3 ruby-on-rails-4


    【解决方案1】:

    获取报告的快速方法是:

    def store
      errors = []
      @data.each do |invite|
         new_member = MemberInvitation.new(:email => invite['email'])
         errors.push(new_member) unless new_member.save
      end
      if errors.empty?
        #everything went fine
      else
        # you have all members with issues in the array
        # I advise you to create your json yourself
      end
    end
    

    【讨论】:

    • Bur create 将最后一封电子邮件存储在数据库中而不给出任何错误消息!!!它应该在哪里显示错误消息而不是存储到数据库中!!!
    • 保持冷静。有什么问题?如果有一个错误,您不希望任何成员持续存在吗?
    • @RubyOnRails new 只会启动一个对象,在那一行还没有保存到 db 中
    • @apneadiving 抱歉,在您编辑答案后,它工作正常!!!感谢您更快地重播......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多