Polyov
Polyov

Reputation: 2311

Rails rolls back valid object

I've got (what I thought was) a very standard object to be saved in Rails 4:

create_table "games", force: true do |t|
    t.string   "sport",      default: "",    null: false
    t.string   "opponent",   default: "",    null: false
    t.datetime "date"
    t.integer  "home_score", default: 0,     null: false
    t.integer  "op_score",   default: 0,     null: false
    t.boolean  "active",     default: true,  null: false
    t.boolean  "final",      default: false, null: false
    t.datetime "created_at"
    t.datetime "updated_at"
end

The object itself:

sport: "Foosball", opponent: "New York", 
date: "2013-12-31 00:00:00", 
home_score: 100, op_score: 0, active: false, final: true,

game.rb:

class Game < ActiveRecord::Base
    validates_presence_of :opponent, :sport
    before_save :check_active
    scope :active, -> { where(active:true) }

    def check_active
      if self.date <= (Date.today - 4)
         self.active = false;
      end
    end
end

However, when I go to save the object:

pry(#<GamesController>)> @game.save
(0.1ms)  begin transaction
(0.1ms)  rollback transaction
    => false
[14] pry(#<GamesController>)> @game.errors.messages
    => {}

What is going on? I've noticed the server also returns 422 unproccessable entity, but I'm not sure how that's happening. The object seems fine in all respects.

Upvotes: 0

Views: 27

Answers (1)

Alex
Alex

Reputation: 641

I think your check_active returns false, that prevent saving. You can obviously return true:

def check_active
  if self.date <= (Date.today - 4)
     self.active = false;
  end
  true
end

Callbacks documentation:

Canceling callbacks

If a before_* callback returns false, all the later callbacks and the associated action are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last.

Upvotes: 1

Related Questions