Forum: Ruby on Rails Tweak relationships & AR loading question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
28c315da59bc0bc0a544ed4a75ad26e9?d=identicon&s=25 Pierre-Alexandre Meyer (Guest)
on 2007-03-20 23:58
(Received via mailing list)
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 Meyer |
| email : pam@mouraf.org |
`========================'
28c315da59bc0bc0a544ed4a75ad26e9?d=identicon&s=25 Pierre-Alexandre Meyer (Guest)
on 2007-03-21 11:52
(Received via mailing list)
On Tue, Mar 20, 2007 at 11:57:32PM +0100, Pierre-Alexandre Meyer 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? :/

--
,========================.
| Pierre-Alexandre Meyer |
| email : pam@mouraf.org |
`========================'
This topic is locked and can not be replied to.