0

I was wondering If I could modify objects using a class method.

For example, users = User.scoped # This will select all the objects

And, suppose, I want to assign a variable for each of the object there is. Let's say, I want them to share a single value. So, when I try to access, for example, users.first.my_variable it would produce the value, I want.

My naive implementation:

def self.set_my_variable(variable_value) 
    scoped.tap do |obj|
       obj.my_variable = variable_value
    end   
end

So, ideally, when I wan't this variable to be set, I should call the class method like this: users.set_my_variable("hello, stackoverflow")

But, when I try accessing the variable through arbitrary object of the set, like this:

users.first.my_variable

I get nil. Comparing .object_id's in both: obj.object_id and users.first.object_id shows that they are different. Why so ? I thought that they share the same reference (pointing to the same objects)

Any way of fixing it (preferrably without passing a collection to this class method) ?

Dmitri
  • 2,451
  • 6
  • 35
  • 55

1 Answers1

0

you need to save object to database:

   obj.my_variable = variable_value
   obj.save
arnage
  • 173
  • 2
  • 9
  • Even when I update "virtual" attributes (variables) ? This is weird. Isn't there anything simplier ? I should have clearly stated that "my_variable" is VIRTUAL. It is used for internal purposes. – Dmitri Aug 14 '13 at 13:40