3
votes

I have models in my app:

class Comment < ActiveRecord::Base

belongs_to :commentable, :polymorphic => true

end

class Project < ActiveRecord::Base

has_many :discussions, :dependent => :destroy
has_many :tickets, :dependent => :destroy

end

class Discussion < ActiveRecord::Base

has_many :comments, :as => :commentable, :dependent => :destroy

end

class Ticket < ActiveRecord::Base

has_many :comments, :as => :commentable, :dependent => :destroy

end

Everything works fine, but sometimes it's not very convinient to get project from comment through commentable, i.e. comment.commentable.project. Is there any way to make has_one project in Comment model?

1

1 Answers

4
votes

I would add the following method to your class Comment:

def project
  self.commentable ? self.commentable.project : nil
end

This will give you the same result without all the magic of ActivRecord.