tabaluga
tabaluga

Reputation: 1417

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 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

Answers (2)

Jeff Perrin
Jeff Perrin

Reputation: 8094

  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

Upvotes: 1

tabaluga
tabaluga

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

Related Questions