views:

74

answers:

2

How to initialize variables in ActiveRecord class? Variables here is the variables that are outside the scope of database

such as:

class Product
  attr_accessor :used
end

I want to initially assign @used initially to false, later if some person access the product, i will change @used to true

First i thought of putting @used=false in initialize method, but it does not get called.

+1  A: 

Define a method called :after_initialize

class User < ActiveRecord::Base
  def after_initialize
    @used = false
  end
end

It will be called (ahem) after the initialize method

Hope this helps

flitzwald
thank you, that works very well
Hadi
+2  A: 
attr_accessor_with_default :used, false

Or if you want to use initialize approach you can define callback after_initialize

def after_initialize
  @used = false
end

Using attr_accessor_with_default with an object literal (e.g. attr_accessor_with_default :used, false) is unsafe to use with any mutable objects. Specifically, it means that different instances of your class will have the same object as their default value. This is sort of like trying to use a class variable (@@my_var) where you want an instance variable (@my_var). If you want to use a mutable object (e.g. a String, Array, or Hash), you must use the block syntax:

attr_accessor_with_default(:used) { Array.new }
Andrius
the first one does not work correctly. if the default value is Array.new, i wonder why?attr_accessor_with_default :some_val, Array.newand the 2nd one works perfectly, thank you
Hadi
Remember attr_accessor_with_default uses the value. Array.new is a simple value, and the reference is copied. I suspect attr_accessor_with_default accepts a block for such a case. It does: http://api.rubyonrails.org/classes/Module.html#M000043
François Beausoleil