Before_create not working
I have the following model setup. But from what I can tell in开发者_JAVA百科 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.
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.
It should be
class Bracket < ActiveRecord::Base
before_create :set_round_to_one
def set_round_to_one
self.round = 1
end
end
Both Zabba and vinceh's solutions are correct, but instead of a before create, I would suggest that you set a default value in your database for the round
attribute of Bracket
.
精彩评论