Instantiate record in single table inheritance

Hi,

is there a way to instantiate a concrete subtype from within an
ActiveRecord collection?

Example:

class Link < ActiveRecord::Base
end

class InternalLink < Link
end

class ExternalLink < Link
end

internal_link = my_navigation.links.create_[xxxxxxx]
external_link = my_navigation.links.create_[xxxxxxxx]

the [xxx] is what I am missing…

I could do this

external_link = my_navigation.links.create(:type => ExternalLink.to_s)

but in this case the validations of ExternalLink will no be processed,
only of Link…

please help argh

cheers
peter

Might be misunderstanding you, but you should be able to do simply:
ExternalLink.new instead of Link.new(:type =>ExternalLink.to_s)

As far as the create goes, I’ve guessing your MyNavigation model has a
has_many :links, and so there will be a links method for instances of
this model, but no method called external_links.

I would think however you could do something like (and haven’t tested
this):

ext_link = ExternalLink.new(:url => “link_details”)

my_navigation << ext_link

HTH

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs