The Rails Guide is one of the best, so I suggest you start reading Polymorphic Associations
You class declarations look fine, and I assume you are also migrating. But just for the sake of it. Let's say it looks like this:
class CreateComment < ActiveRecord::Migration def change create_table :comments do |t| t.string :name t.references :commentable, :polymorphic => true
No, if you have an Article or Photo object and you want to get comments on this object, then the Thilo suggestion will be correct. All you have to do is the following: @jims_photo.comments
If, on the other hand, you have an instance of the Comment model, you can get the parent element as follows: @comment.commentable . But if you want comments on Jim's photos to do the best thing. Otherwise, you need to specify the arguments as :commentable_id and commentable_type . I do not know a single crawler that extends a polymorphic object into the commentable_id and commentable_type fields for you.
But you can always create a class method for this:
def self.find_by_parent(parent) where(:commentable_id => parent.id, :commentable_type => parent.class.name) end
source share