1

I have two models Board and Pictures and I want a user to be able to comment on either the Board as a whole or the individual Pictures.

My polymorphic Comment model:

 class Comment < ActiveRecord::Base
     belongs_to :commentable, polymorphic: true
 end

and then I have a simple has_many in each of the other models:

 class Board < ActiveRecord::Base
     has_many :comments, as: :commentable, dependent: :destroy
     has_many :pictures

 class Pictures < ActiveRecord::Base
     has_many :comments, as: :commentable, dependent: :destroy
     belongs_to :board

What I really want to be able to do is add a new scope called something like all_comments which combines the comments from the Board model with the related comments from the Pictures model. I can do this with a method, but I end up with an array and not a scoped relation.

My method:

def all_comments
    comments = self.comments
    return comments + self.pictures.map {|x| x.comments}.flatten
end

How can I return a scoped relationship that can chain the results?

JG in SD
  • 5,427
  • 3
  • 34
  • 46
JoshL
  • 1,397
  • 1
  • 12
  • 28

2 Answers2

4

first of all Pictures should be singular.

secondly, you can just call a finder on Comment to get all the comments you want

Comment.where("type = 'board' AND id IN(?) OR type = 'picture' AND id IN(?)", self.id, self.pictures.map(&:id))

or something like that.

phoet
  • 18,688
  • 4
  • 46
  • 74
0

phoet's answer intrigued me (I +1'd), so here's my refactor / expansion on what he suggested:


You'd look in the Comment model to pull out the relevant comments. To do this, you need to firstly know the board & the pictures associated with it. Phoet uses the self.pictures object for this:

#app/models/comment.rb
Class Board < ActiveRecord::Base
    def all_comments
        ids = self.id + self.pictures.map(&:id)
        Comment.find(ids)
    end
end

This will find the ids in the comment model, returning the data as a collection. If you wanted a true representation of the comments (hierarchical), you'd have to use some sort of ancestry / inheritance structure I think

Richard Peck
  • 76,116
  • 9
  • 93
  • 147
  • No this wouldnt work, but interesting try. It would match IDs from other models that are also using the Comments model. – JoshL Apr 25 '14 at 12:00