0

我有一个Project模型,它有很多poststasks. 两者posts兼有。tasks_ attachments附件是多态的。如何查询单个项目的所有附件?

显然这行不通,因为我们没有attachable桌子;我们有poststasks。它还产生一个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
4

0 回答 0