0

I am implementing this solution as an alternative to polymorphism.

Why can you not have a foreign key in a polymorphic association?

But I am wondering if there is an easy way to go:

Article.comments instead of Article.commentable.comments

Community
  • 1
  • 1
Dex
  • 12,527
  • 15
  • 69
  • 90

1 Answers1

3

You should be able to use delegate to pass method calls on to another object.

class Article < ActiveRecord::Base
  has_one :commentable

  delegate :comments, :to => :commentable
end

Edit:

I'm assuming you don't mean to use the constant Article in your example, because that wouldn't work either way. These methods are instance methods and need to be used as:

article = Article.first

article.commentable.comments
article.comments (Equivalent to above)
Peter Brown
  • 50,956
  • 18
  • 113
  • 146
  • Yes, this is what I was looking for. Is there a way to alias comments? My actual models lend themselves to inconvenient names. So could I make article.aliased == article.commentable.comments? – Dex Nov 18 '10 at 13:13
  • Perhaps scopes would be better for this. – Dex Nov 18 '10 at 13:32
  • @Dex In typical ruby fashion, there's a few different ways you could alias the comments name. Do you want the same alias for all commentable objects or do you want unique aliases for each one? – Peter Brown Nov 18 '10 at 13:43
  • The same alias is fine. I just want to be able to go object.comments – Dex Nov 19 '10 at 04:46
  • If you wanted to call it something different, you could create a method in each class in addition to using delegate. The method would just return `comments` and you could name it whatever the alias would be. If you want this for all models, you'd have to add it to each one, or just change the association in Commentable to be `has_many :new_comments, :class_name => "Comment"` – Peter Brown Nov 19 '10 at 13:50