通过双层has_many关系检索结果集

时间:2012-08-09 23:05:52

标签: ruby-on-rails ruby-on-rails-3 activerecord

我有三种模式:

  • 用户
  • 文件
  • 下载

User has_many FilesFile belongs_to User

File has_many DownloadsDownload belongs_to User

有没有办法检索所有User的{​​{1}},而不是遍历所有Downloads,然后检索与每个文件关联的Files? (这会产生大量的查询)

修改

我发现只需3次查询即可加载DownloadsUserFiles

Downloads

但是,如果我已经有user = User.includes(:uploads => [:downloads]).find(1) 个对象怎么办?

如果我只是想在不加载上传的情况下加载用户下载怎么办? (使用连接)

修改

User

有没有办法直接引用users表主键?

1 个答案:

答案 0 :(得分:4)

你试过吗

class User
  has_many :downloads, :through => :files
end