Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

has_one :through polymorphic - is it possible?

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?

like image 246
Link_er Avatar asked Jun 12 '26 15:06

Link_er


1 Answers

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.

like image 81
mliebelt Avatar answered Jun 14 '26 06:06

mliebelt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!