我有一个需要做一个查询记录集,并获得许多类型的对象列表。正确的协会设计
在这个例子中,我将使用博客文章,其中有许多不同类型的博客文章。
基地邮编:
class Post < ActiveRecord::Base
belongs_to :postable, :polymorphic => true
attr_accessible :body, :title
end
音频后期:
class AudioPost < ActiveRecord::Base
attr_accessible :sound
has_one :postable, :as => :postable
end
图文帖子:
class GraphicPost < ActiveRecord::Base
attr_accessible :image
has_one :postable, :as => :postable
end
这会让我做这样的事情。
@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
虽然这个工作,但检查类型,因为这是违反鸭式原则,感觉不对。我会认为有更好的办法可以做同样的事情。
什么是更好的设计来实现这个相同的目标还是我只是在想我的设计?
继承更适合我在这种情况下,你为什么要选择多态关联? – juanpastas
我想你知道STI,'AudioPost
juanpastas
欢迎来到Rails城市的限制。如果你走得更远,你可能会发现自己哼唱Sinatra先生的曲调。 – 2013-05-19 20:25:26