Hadi
Hadi

Reputation: 103

initializing variables in ActiveRecord's classes

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.

Upvotes: 1

Views: 3571

Answers (2)

Andrius
Andrius

Reputation: 2818

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 }

Upvotes: 3

flitzwald
flitzwald

Reputation: 20240

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

Upvotes: 1

Related Questions