ruby on rails - Proper Association Design -


i have need 1 query on record set , list of many type objects.

in example use blog post blog post has many different types.

base post:

class post < activerecord::base   belongs_to :postable, :polymorphic => true   attr_accessible :body, :title end 

audio post:

class audiopost < activerecord::base   attr_accessible :sound   has_one :postable, :as => :postable end 

graphic post:

class graphicpost < activerecord::base   attr_accessible :image   has_one :postable, :as => :postable end 

this allow me this.

@post = post.all @post.each |post|   post.title   post.body   post.postable.image if post.postable_type == "graphicpost"   post.postable.sound if post.postable_type == "audiopost"  end 

though works, feels wrong check type because goes against duck type principle. assume there better way same thing.

what better design achieve same goal or on thinking design?

see comments.

anyway, if want polymorphic, write logic in model:

class post   delegate :content, to: :postable   class audiopost   alias_method :sound, :content   class graphicpost   alias_method :image, :content 

you want render images different sound, part, use helper:

module mediahelper   def medium(data)     case # make case detecting data type     # print data.class see if can discriminate that. 

and call in view

= medium post.content 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -