0

我需要对记录集进行一次查询并获取许多类型对象的列表。

在这个例子中,我将使用一篇博文,其中博文有许多不同的类型。

基本职位:

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

虽然这样可行,但检查类型感觉不对,因为这违背了鸭子类型原则。我会假设有更好的方法来做同样的事情。

什么是更好的设计来实现同样的目标,或者我只是在思考我的设计?

4

1 回答 1

2

看我的评论。

无论如何,如果你想要多态,我会在模型中编写逻辑:

class Post
  delegate :content, to: :postable


class AudioPost
  alias_method :sound, :content


class GraphicPost
  alias_method :image, :content

你会想要渲染不同于声音的图像,对于这部分,我会使用一个助手:

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.

并在视图中调用

= medium post.content
于 2013-05-19T20:28:49.260 回答