我有以下设置:
公司 has_many :locations
位置所属:公司
当我调用 Company.includes(:locations) 时,我得到了返回的公司,但没有关联的位置。
任何想法表示赞赏!
最佳答案
Eager Loading 是必要的,因为它可以优化您的应用程序的性能并防止您的系统遇到 N+1 查询问题。假设您的数据库中有 3000 家公司,那么您的数据库将被 3000+1 个查询淹没。所以在 Controller 中你可以实现它
@companies = Company.includes(:locations)
同样对于单个公司,您可以这样做
@company = Company.includes(:locations).find(params[:id])
现在位置将被急切地加载,您可以将它们作为
@companies.collect{ |company| company.locations }
或者
@company.locations
Note you can use any iterator. I used 'collect' just for the purpose of elaboration. Thanks
关于ruby-on-rails - Rails .includes 不返回关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38621164/