So, if I have a polymorphic association throughout my application, is there a way to add methods to it? For instance, if :post, :photo and :user are all associated to :rankings with a polymorphic association named :rankable, can I somehow create methods on :rankable that would then be inherited by :post, :photo or :user? My guess is that, if it is possible, it would require me adding a Rankable model to the app and defining methods within it. Is that possible? If so, and I am correct in needing to create a model, what class would that model inherit from or how would I define it as being that polymorphic relationship?
+1
A:
I don't know how you'd do this with a model, but you can easily add methods with mixins:
module RankableMethods
def do_something_useful
...
end
end
class Post < ActiveRecord::Base
include RankableMethods
belongs_to :rankable, :polymorphic = true
end
p = Post.new
p.respond_to?(:do_something_useful) # true
zetetic
2010-10-02 04:04:33
A:
You have to separate the concepts of 'polymorphic' as it applies to an ActiveRecord polymorphic association, and 'polymorphic' in the classic OOP sense of inheritance.
A 'Rankable' polymorphic type in the first sense doesn't exist except as a database convention within ActiveRecord that lets a record in one table refer to records in multiple possible other tables. If you want to express this abstraction more specifically in your object model -- polymorphism in the second sense -- you'll have to declare a separate Class or Module that your 'Rankable' ActiveRecords can mix in or inherit from.
Dave Sims
2010-10-02 04:37:27