Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ERROR: current transaction is aborted, commands ignored until end of transaction block, Ruby on Rails

I have a model Car in my application. I've added color field. My migration looks like this:

class AddColorToCars < ActiveRecord::Migration
  def change
    add_column :cars, :color, :string
    Car.all.each do |car|
      car.color = "silver"
      car.save
    end
  end
end

in my form I've add:

= f.input :color

and in Car model I've added validation:

validates :color, presence: true

When I try edit existing Car and change his color to be nil I have the following error:

ERROR: current transaction is aborted, commands ignored until end of transaction block

When I disable my validation everything works fine. What's wrong?

like image 591
Mateusz Urbański Avatar asked Jun 02 '14 13:06

Mateusz Urbański


1 Answers

This is all related to the transactions in Rails with PostgreSQL.

On some database systems, such as PostgreSQL, database errors inside a transaction cause the entire transaction to become unusable until it’s restarted from the beginning.

You have a transaction aborting that is being caught. This is sometimes caused when adding validations on ActiveRecord models. For a reason, you can’t create anything on a table in a transaction once you break the INSERT for PostgreSQL. Also, adding validations sometimes breaks the INSERT.

Quick Solution: Restart your Rails server and your validations will work flawlessly.

like image 107
Oss Avatar answered Oct 23 '22 11:10

Oss