开发者

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 :u开发者_运维百科sed
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.


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 }


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜