ActiveRecord验证无效

时间:2015-12-31 14:02:21

标签: ruby-on-rails ruby validation rails-activerecord

我已经创建了Rails ActiveRecord验证,当它被违反时,没有保存任何记录(实际上,我相信它正在保存,然后在控制台输出中看到正在完成ROLLBACK)。

但是,不是再次重定向到新表单并显示我添加的错误消息,而是发送到索引页面(没有创建新记录,这是正确的,但我想要其他行为)。

我认为这是一个愚蠢的事情,与回滚相关(就像记录正在保存,这就是为什么我被重定向到索引页面,但随后回滚完成 - 不知道为什么,并且没有记录是保存)。知道如何解决这个问题吗?

我已经创建了以下验证:

  # Adds an error if the replacement date is in the future
  def replacement_date_is_not_future
    unless replacement_date.blank? or replacement_date <= Date.today
      errors.add(:replacement_date, :date)
    end
  end

在我的模型的头部,我有以下内容:

  validate :replacement_date_is_not_future

这是我的控制器方法:

  def create
    @device_replacement = DeviceReplacementForm.new(replacement_params)

    if @device_replacement.save
      redirect_to device_replacements_path
    else
      render 'new'
    end
  end

这是我的控制台输出:

Started POST "/device_replacements" for 127.0.0.1 at 2015-12-31 10:48:09 -0300
Processing by DeviceReplacementsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"MbR2lXp5ujSNILEKC2ROhij3+yNpIL3ymEdZxJejSxc=", "device_replacement_form"=>{"old_esn"=>"2-3021325", "new_esn"=>"DEMO-0-648340", "replacement_date"=>"2016-01-03"}, "commit"=>"Create"}
  RackCAS::ActiveRecordStore::Session Load (0.9ms)  SELECT  "sessions".* FROM "sessions"  WHERE "sessions"."session_id" = '0ee02a1bcbc8548e172d511c02b97490'  ORDER BY "sessions"."id" ASC LIMIT 1
  Device Load (1.1ms)  SELECT  "devices".* FROM "devices"  WHERE "devices"."esn" = '2-3021325' LIMIT 1
  Device Load (1.6ms)  SELECT  "devices".* FROM "devices"  WHERE "devices"."esn" = 'DEMO-0-648340' LIMIT 1
   (0.3ms)  BEGIN
   (0.5ms)  SELECT "devices"."asset_id" FROM "devices"  WHERE "devices"."id" = 81265
   (0.3ms)  ROLLBACK
Redirected to http://localhost:3000/device_replacements
Completed 302 Found in 93ms (ActiveRecord: 14.8ms)
  RackCAS::ActiveRecordStore::Session Load (1.9ms)  SELECT  "sessions".* FROM "sessions"  WHERE "sessions"."session_id" = '0ee02a1bcbc8548e172d511c02b97490' LIMIT 1
   (0.3ms)  BEGIN
   (0.4ms)  COMMIT

1 个答案:

答案 0 :(得分:0)

看起来你的代码很好,事情是不是在正确的地方。试着看看是否有另一个模型负责在该视图中创建device_replacement。

希望它有所帮助。