Tweak relationships & AR loading question

Hi,

Imagine you have a model Guy. Pick a guy from your table.
Maybe he is married and have children (single guys can’t have children,
can they?). So your are tempted to write:

class Guy < ActiveRecord::Base
has_many :children
end

But if he is single, he can’t have children. So you wan’t to write:

class Guy < ActiveRecord::Base
if self.single
has_many :children
else
has_one :child
end
end

This could work: in fact has_* is just a macro for a bunch of specific
define_method. I am wrong?

But it doesn’t: the loading of the class fails claiming for
NoMethodError: undefined method `single’
I don’t understand: does AR loads relationships before defining
accessors? And if I force attr_accessor :single, assuming AR will
override it, I’ve got the same error. Does he parses the whole class
seeking for relationship first?

Thanks for your help,


,========================.
| Pierre-Alexandre M. |
| email : [email protected] |
`========================’

On Tue, Mar 20, 2007 at 11:57:32PM +0100, Pierre-Alexandre M. wrote :

But it doesn’t: the loading of the class fails claiming for
NoMethodError: undefined method `single’
I don’t understand: does AR loads relationships before defining
accessors? And if I force attr_accessor :single, assuming AR will
override it, I’ve got the same error. Does he parses the whole class
seeking for relationship first?

After going deeper in the source code, @attributes =
attributes_from_column_definition is called in the initialize method of
ActiveRecord::Base.

Actually, during the loading of the class, there is first:

ActiveRecord::Base.class_eval do
include ActiveRecord::Validations
…/…
include ActiveRecord::Associations
…/…
end

@attributes is not initialized yet.
I thought ActiveRecord::Validations could help me, to see how it handles
passed attributes, but I didn’t understand the validates_each method
(line 291). What’s the send method? :confused:


,========================.
| Pierre-Alexandre M. |
| email : [email protected] |
`========================’