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