ruby on rails - What is the best way to create a DRY content model hierarchy? -
i have content management system ios app built rails. right there 3 different types of content. first 2 strings uploaded textfield user. 1 twitter handles , hashtags, other urls. second type photos.
the user can upload many individual instances of these types content he/she wants given feed passed ios app via api call display.
the current approach using have feed, picture, twitter, , webpage models. when user crates new feed, associate appropriate content feed via 1 many relationship between each feed instance it's content instances.
when comes time display content user has uploaded, request given stream generated , feed model following awful thing determine type of content should shown:
def feed.get_content_for_feed(feed_id) return self.map_type_to_class(feed_id).get_content_for_feed(feed_id) end private def feed.map_type_to_class(feed_id) feed_type_id = feed.find(feed_id).feed_type_id not_yet_implemented = nil case stream_type_id when 1 return webpages when 2 return pictures when 3 return not_yet_implemented when 4 return twitter when 5 return not_yet_implemented when 6 return not_yet_implemented when 7 return not_yet_implemented when 8 return not_yet_implemented else return nil end end then each content class implements get_content_for_feed method return content:
def twitter.get_content_for_feed(feed_id) tweet_urls = self.where(:feed_id => feed_id.to_i) if tweet_urls.empty? return [] else return tweet_urls end end so returns appropriate class. works, know wrong, not sure doing.
how work you
class user has_many :feeds has_many :twitters, through: :feeds, source: :feedable, source_type: 'twitter' has_many :webpages, through: :feeds, source: :feedable, source_type: 'webpage' has_many :pictures, through: :feeds, source: :feedable, source_type: 'picture' end class feed belongs_to :user belongs_to :feedable, polymorphic: true end now feeds table need feedable_id , feedable_type associations work expected. e.g.
website.create name: "website", url: "http://www.example.com" user = user.create name: "user" feed = user.feeds.build feed.feedable = website.find_by_name("website") feed.save i don't have ton of experience sort of has_many through polymorphic conceptually should work you. in case not solve problem there ton of questions , articles if google polymorphic has_many through.
Comments
Post a Comment