多态关联的别名

Aliasing names of polymorphic associations

我第一次尝试在项目中实现多态关联,但我不喜欢关联的读取方式,想知道是否有别名的方法?

示例:

# app/models/comment.rb
class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
end

# app/models/post.rb
class Post < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

# app/models/picture.rb
class Picture < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

假设我想从给定的评论中检索 Post 实例,terrific_post = Comment.first.commentable 在我看来读起来不太好。有没有办法在 Comment 模型中为不同的关联名称起别名,避免依赖单一名称,例如 commentable?我知道你可以选择一个更符合你的特定 dsl 的名称,而不是说“可评论”,但是我更愿意继续根据它们的关系来引用与名称(或变体)的关联,类似于 Comment.first.post 和`Comment.first.picture' 如果可能的话。

归根结底,多态关联所带来的灵活性并不是很大的牺牲。只是好奇是否存在解决方案。

注意:以下示例取自 The Odin Project,它很好地解释了各种类型的关联。

您可以像任何其他方法一样为关联设置别名:

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
  alias_method :post, :commentable
  alias_method :picture, :commentable
end

然后您可以执行 Comment.first.postComment.first.picture

但是 Comment.first.post 可以是 PostPicture, 所以你应该知道你在做什么。

另一种方法是仅当 commentablePost 时才实施 return post 的方法,而仅当 commentablecommentable 时才实施 picture 的方法Picture:

class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true

  def post
    commentable if commentable.is_a? Post
  end

  def picture
    commentable if commentable.is_a? Picture
  end
end

为了实验目的,我最终将我的解决方案打包成 gem。欢迎尝试。