0

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
tabaluga
  • 1,377
  • 4
  • 20
  • 27

2 Answers2

1
  1. First off, see this question: What is the best way to set default values in activerecord
  2. 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
  3. 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
Community
  • 1
  • 1
Jeff Perrin
  • 8,094
  • 1
  • 23
  • 19
0

just found it in the api

def setup_values 
  write_attribute :style, "hardcore" if style.blank?  
end

tadaa and it works :)

tabaluga
  • 1,377
  • 4
  • 20
  • 27