Hey All,
Say I have a website with articles and events and I want to create an
index of featured items which will have a mixture of articles and
events. I presume I’d create a FeaturedItem model/table with the
following:
featured_class <-- ‘Article’ or ‘Event’
featured_id <-- id of Article or Event
position <-- position in featured list
When I pull the featured items from the database, I’m gonna wanna pull
the corresponding item from the featured_class table. What’s the best
way to do this, other than:
if FeaturedItem.featured_class == ‘Article’
Article.find()…
elsif FeaturedItem.featured_class == ‘Event’
Event.find()…
end
Is there anyway to create functionality that will allow me to do
something like this:
FeaturedItem.featured_class.find()…
or something similar
???
What you want is a polymorphic association between Feature? and both
Article and Event. Check out the Rails API for ActiveRecord::Base and
look for the heading “Polymorphic Associations”
the corresponding item from the featured_class table. What’s the best
FeaturedItem.featured_class.find()…
class Article < ActiveRecord::Base
has_one :featured_thing, :as => :featureable
end
class Event < ActiveRecord::Base
has_one :featured_thing, :as => :featureable
end
id :integer
featureable_id :integer
featureable_type :string
class FeaturedThing < ActiveRecord::Base
belongs_to :featureable, :polymorphic => true
def featureable_thing
self.featurable_type.constantize.find_by_id(self.featurable_id)
end
end
Maybe?
Then you could do say…
FeaturedThing.find(:all).each do |ft|
puts ft.featureable_thing.title # assuming both Articles and Events
have
# a title
end