Search code examples
mysqlsqlruby-on-railsrubymodels

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?


Solution

  • 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)