简体   繁体   中英

One db query on associative models ruby on rails

I am using Ruby on Rails. In my file sharing application I have a model structure that looks like this:

User has many Entities
Entity belongs to User
Entity has many Reports
Report belongs to Entity
Report has many Shares
Share belongs to Report

Now when I have a share_id, how can I extract the User, Entity and Report information for that share_id in one db query? And is it better to do 3 simple queries or one complex join-type query?

I think using includes like this should work:

Share.includes(report: { entity: :user }).find(share_id)

see also this question: ActiveRecord Includes

Update
Apparently the correct API for what you need is eager_load

Share.eager_load(report: { entity: :user }).find(share_id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM