如何查询特定项目的附件

时间:2013-09-23 18:04:19

标签: ruby-on-rails ruby activerecord polymorphism

我有Project模型,其中包含许多poststaskspoststasks都有很多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

0 个答案:

没有答案