Forum: Ruby on Rails Featured Items Listing

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.
jstepper (Guest)
on 2007-02-28 23:56
(Received via mailing list)
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
???
dan choi (Guest)
on 2007-03-01 04:03
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"
Philip H. (Guest)
on 2007-03-01 06:26
(Received via mailing list)
> 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
This topic is locked and can not be replied to.