我有一个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