How do I set attributes in an ActiveRecord Object only if it is nil?
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 st开发者_如何学Cyle
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
- First off, see this question: What is the best way to set default values in activerecord
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
- Lastly write the assignment to self.style like so:
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
just found it in the api
def setup_values
write_attribute :style, "hardcore" if style.blank?
end
tadaa and it works :)
精彩评论