Reputation: 48706
There are 3 models, say Article, Picture and Comment. Comment is the polymorphic model, of course.
Now, i can do something like @article.comments and grab the comments, but if i have a comment, how can i know if it originates from an article or picture ? The db only holds an id. I tried that (http://guides.rubyonrails.org/association_basics.html#polymorphic-associations), but just got back nil on commentable.
Moreover, how can i move a picture comment to an article comment ? The comment is bound with a particular article id on commentable_id, how can i change that particular comment to becoming a comment for a specific picture ?
EDIT: I TRIED THAT AND DID NOT WORK
ruby-1.9.2-p180 :001 > user = User.find_by_username('name')
ruby-1.9.2-p180 :002 > user.owned_items
=> [#<OwnedItem id: 81233384, ownable_id: 861022540, user_id: 986759322, ...
ruby-1.9.2-p180 :003 > user.owned_items[0].ownable
=> nil
Upvotes: 0
Views: 245
Reputation: 882
def Article < ActiveRecord::Base
has_many :comments, :as => :commentable
end
def Picture < ActiveRecord::Base
has_many :comments, :as => :commentable
end
def Comment < ActiveRecord::Base
belongs_to :commentable, :polymorpic => true
end
But you probably was already so far ;) Now you can do something like comment.where(:commentable_type => 'Event').commentable
and it will return Event for a comment.
Upvotes: 1