我有Project
模型,其中包含许多posts
和tasks
。 posts
和tasks
都有很多attachments
。附件是多态的。如何查询单个项目的所有附件?
显然这不起作用,因为我们没有attachable
表;我们有posts
和tasks
。它还会生成can't eager load polymorphic association 'attachable'
。
# project.rb
def attachments
Attachment.joins(:attachable).where('attachable.project_id = ?', id)
end
其余代码:
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