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?