Reputation: 1417
Sorry, I think I am a bit stupid today
class Mutant < ActiveRecord::Base
attr_accessible :style
before_create :setup_values
private
def setup_values
style = "hardcore" unless style
end
end
I like to call this stuff in the console like
Mutant.create(:style => "rampage") # expected is Mutant.first.style == "rampage"
Mutant.create # expected is Mutant.last.style == "hardcore but this doesn't work
Upvotes: 0
Views: 1989
Reputation: 8094
style = "hardcore" unless style
will instantiate a new variable named 'style' rather than setting the existing property. Change it to reference self like so: self.style = "hardcore" unless style
self.style ||= "hardcore"
which is a shortcut for what you've currently written.I'd probably write it like this:
class Mutant < ActiveRecord::Base
attr_accessible :style
after_initialize :setup_values
private
def setup_values
self.style ||= "hardcore"
end
end
Upvotes: 1
Reputation: 1417
just found it in the api
def setup_values
write_attribute :style, "hardcore" if style.blank?
end
tadaa and it works :)
Upvotes: 0