Ruby on rails 如何查询特定项目的附件

Ruby on rails 如何查询特定项目的附件,ruby-on-rails,ruby,activerecord,polymorphism,Ruby On Rails,Ruby,Activerecord,Polymorphism,我有一个项目模型,它有许多帖子和任务。帖子和任务都有许多附件。依恋是多态的。如何查询单个项目的所有附件 显然,这不起作用,因为我们没有可附加的表;我们有帖子和任务。它还生成一个无法立即加载多态关联“attachable” # project.rb def attachments Attachment.joins(:attachable).where('attachable.project_id = ?', id) end 代码的其余部分: class Project < Active

我有一个
项目
模型,它有许多
帖子
任务
帖子
任务
都有许多
附件
。依恋是多态的。如何查询单个项目的所有附件

显然,这不起作用,因为我们没有可附加的
表;我们有
帖子
任务
。它还生成一个
无法立即加载多态关联“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
class项目
您的标题具有误导性。您只是想查询给定项目的附件,还是想在查询项目时立即加载附件?我想查询特定项目的所有附件…您看到了吗?