I have a Project
model, which has many posts
and tasks
. Both posts
and tasks
have many attachments
. Attachment is polymorphic. How can I query all the attachments for a single project?
Obviously this doesn't work because we don't have an attachable
table; we have posts
and tasks
. It also produces a can't eager load polymorphic association 'attachable'
.
# project.rb
def attachments
Attachment.joins(:attachable).where('attachable.project_id = ?', id)
end
Rest of code:
class Project < ActiveRecord::Base
has_many :posts
has_many :tasks
end
class Post < ActiveRecord::Base
belongs_to :project
has_many :attachments, as: :attachable
end
class Task < ActiveRecord::Base
belongs_to :project
has_many :attachments, as: :attachable
end
class Attachment < ActiveRecord::Base
belongs_to :attachable, polymorphic: true
end