I am using RoR ActiveRecord polymorphic inheritance and was wondering
if it's possible to access the base class' association methods in the
invocation of either to_xml or to_json without having to depict the
base class data in the serialized string.  Here are my classes:

# base class
class Asset < ActiveRecord::Base
    belongs_to :resource, :polymorphic => true
    has_many :right_owners, :dependent => :destroy
end

# derived class
class Song < ActiveRecord::Base
      has_one :asset, :as => :resource, :dependent => :destroy
end

# derived class
class Film < ActiveRecord::Base
      has_one :asset, :as => :resource, :dependent => :destroy
end


If I instantiate the asset, as in the case of asset = Asset.find
(:first, :include=>:resource), I can easily call asset.to_xml
(:include=>:right_owners).

However sometimes, we absolutely need to have the concrete class and
not just the base class object or serialized state.  If I instantiate
the song, how can I serialize the underlying asset's right_owners data
without introducing the 'asset' as the base class navigational tie?
For example:
# instantiate the song
song = Song.find(:first, :include=>:asset)

# serialize XML or JSON that includes the underlying asset's
right_owners
# I can do this but this but it is not compatible for our caller since
they don't understand the nested base Asset #class
song.to_xml(:include=>{:asset=>{:include=>:right_owners}})
#or alternatively for json:
song.to_json(:include=>{:asset=>{:include=>:right_owners}})

Is there a way to access and serialize the base class' associative
methods, i.e. 'right_owners', without having to include the 'asset'
information.  That is ideally, I'm looking for
<song>
   <title>.....</title>
   <artist>.....</artist>
   <right_owners>
        <right_owners>....</right_owners>
        ....
   </right_owners>
</song>

One workaround is to define the right_owners relationship on the Song
class but that feels redundant and doesn't follow the DRY principle
especially considering there will be other types of derived classes
such as Films, etc...

If I define right_owners as a method on the Song class, it just
serializes the class name as an array rather treating it as a AR
association that I can further navigate.  That is a custom method is
not being treated the same as the AR association method defined
with :has_one or :has_many.

Any insight is much appreciated.  Thanks.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to