Forum: Ruby on Rails Overriding a Relationships Propertry

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.
MaggotChild (Guest)
on 2009-04-27 03:58
(Received via mailing list)
I have a child relationship that is denormalized. I want to normalize
it at the object level once it's retrieved:

class Parent
  has_many :denormalized_children,  :class_name=>'Child'

  def children
    if @normalized_children.nil?
       @normalized_children = []
       denormalized_children.group_by(&:number).each { |c|
            @normalized_children << NormalizedChild.new(c)
       }
    end
    @normalized_children
  end
end

This works fine, but I don't want to eager load them
as :denormalized_children. I'd like to use :children. So I tried:

class Parent
  has_many :children

  alias :denormalized_children :children
  def children
  #Same definition
  end
end


AR doesn't like this as it expects the children prop to return
something that responds to loaded.

has_many :children, :group=>'number'

doesnt work either since it discards all but  N unique numbers. So if
I have 10 with number 1 and 5 with number 2 I'll only get back 2
children.

Is there any way to do this without having to change the name of the
relationship?

I can't use after_load  (or whatever it's called) in the Child class
since the children need to be grouped by their relationship to their
parent.

Any suggestions would be great.

Thanks
This topic is locked and can not be replied to.