Reputation: 2902
I have a need to do one query on a record set and get list of many type objects.
In this example I will use a blog post which a 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 will allow me to do something like this.
@post = Post.all
@post.each do |post|
post.title
post.body
post.postable.image if post.postable_type == "GraphicPost"
post.postable.sound if post.postable_type == "AudioPost"
end
Though this works, it feels wrong to check the type because that goes against the duck type principle. I would assume there is a better way then this to do the same thing.
What is be a better design to achieve this same goal or am I just over thinking my design?
Upvotes: 0
Views: 88
Reputation: 21785
See my comments.
Anyway, if you want polymorphic, I would write logic in model:
class Post
delegate :content, to: :postable
class AudioPost
alias_method :sound, :content
class GraphicPost
alias_method :image, :content
You will want to render images different than a sound, for that part, I would use a helper:
module MediaHelper
def medium(data)
case # make your case detecting data type
# you could print data.class to see if you can discriminate with that.
and call in view
= medium post.content
Upvotes: 2