如果@ model.save抛出错误,则为Rails

时间:2014-11-18 20:34:00

标签: ruby ruby-on-rails-4

我有一个消息模型。每当我在控制器中运行if @message.save时,我都会收到此错误:

ERROR:  null value in column "conversation_id" violates not-null constraint

如果保存失败,我只想重定向。

  def create
    @message = Message.new(message_params)
    if @message.save
      # redirect
    else
      # render new
    end
  end 

我的消息架构

  create_table "messages", force: true do |t|
    t.string   "body",                                    null: false
    t.integer  "conversation_id",                         null: false
    t.datetime "created_at"
    t.datetime "updated_at"
  end

1 个答案:

答案 0 :(得分:5)

我认为发生这种情况的原因是因为您的实际模型中没有验证,只有在db中。因此,它正在通过验证继续保存,但db有问题。只需在模型中包含验证,它将返回false:

validates :conversation_id, presence: true
相关问题