how to find parent object_id into child object ?

P

Pokkai Dokkai

suppose a object (obj1) have another object (obj2) itself.
how to find obj1.object_id inside obj2 ?
 
R

Robert Klemme

2008/2/18 said:
suppose a object (obj1) have another object (obj2) itself.
how to find obj1.object_id inside obj2 ?

You can't. Well, you can try but there is no guarantee that you will
find all obj1 that reference obj1 because it won't work for Structs:

irb(main):001:0> S=Struct.new :eek:bj
=> S
irb(main):002:0> s1 = S.new
=> #<struct S obj=nil>
irb(main):003:0> s2 = S.new s1
=> #<struct S obj=#<struct S obj=nil>>
irb(main):004:0> ObjectSpace.each_object(Object) do |obj|
irb(main):005:1* puts obj.object_id if
irb(main):006:1* obj.instance_variables.any? {|iv|
obj.instance_variable_get(iv).equal? s1}
irb(main):007:1> end
=> 4228
irb(main):008:0> s2.object_id
=> 1073522830
irb(main):009:0> s2.instance_variables
=> []
irb(main):010:0>

If obj2 needs to know, you should explicitly tell it.

Kind regards

robert
 
T

ThoML

Well, I'm not sure if I understood the question right. But I think
something like this is possible (struct maybe is a bad choice for
demonstration purposes):

class A
def initialize(o=nil)
@o = o
end
end

Anyway, the proper way probably would be to design the class so that
obj2 gets a reference to obj1 when it is included in obj1 (if you know
it needs such a reference), which is what Robert meant I suppose.
 
P

Pokkai Dokkai

ThoML said:
Well, I'm not sure if I understood the question right. But I think
something like this is possible (struct maybe is a bad choice for
demonstration purposes):

class A
def initialize(o=nil)
@o = o
end
end

Anyway, the proper way probably would be to design the class so that
obj2 gets a reference to obj1 when it is included in obj1 (if you know
it needs such a reference), which is what Robert meant I suppose.

i am a beginner rails developer

in rails archies there is no proper relation between Model and
Controller

inside controller i should create Model object .
At such situation i want to assign some values to model_object
attributes from controller (without argument passing to model_object ) .
like

nowadays i am doing like this
model_object=Record.find:)first)
model_object.updated_by=session[:user]
model_object.save

but i want like this

class Record < AR
before_update :assign_updated_by
protected
def assign_updated_by
self.updated_by=session[:user] #or some idea here
end
end
model_object=Record.find:)first)
model_object.save
.....
any idea...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,571
Members
45,045
Latest member
DRCM

Latest Threads

Top