Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Before_create not working

I have the following model setup. But from what I can tell in the logs, the variable is being saved in the db as null:

class Bracket < ActiveRecord::Base
  before_create :set_round_to_one

  def set_round_to_one
    @round = 1
  end
end

I create it by using something like this:

bracket = Bracket.new(:name => 'Winners', :tournament_id => self.id)
bracket.save

I did use create as supposed to new and save, but it didn't work either.

like image 960
agmcleod Avatar asked Jul 11 '11 01:07

agmcleod


1 Answers

Presuming that round is a field in your brackets table, you need to call the setter:

self.round = 1

That's because round is actually a key into the bracket's attributes Hash and by calling the setter the value in that Hash is set correctly.

Further, with @round = 1, you're simply causing a new instance variable called round to be created the first time it is called. And since ActiveRecord does not look for values in instance variables (it looks in the attributes Hash), nothing happens as far as saving the value of @round is concerned.

like image 151
Zabba Avatar answered Oct 08 '22 17:10

Zabba