简体   繁体   中英

Ruby on Rails Active Record inner join not working

I have 2 models: Engagement, user. Engagement basically refers to the items booked by the user. each engagement is for a specific user. user in engagement has a foreign key. I want to join engagement with user so that i can see the details of the user.

Here are my models

class Engagement < ActiveRecord::Base
  belongs_to :food_item  
  belongs_to :user
end
class User < ActiveRecord::Base
    has_many :engagements
    has_many :food_item, through: :engagements
end

I am running below query:

Engagement.joins("INNER JOIN users ON users.id = engagements.user_id")

It is not joining both the tables.

Any help will be appreciated

Your query is right. You're doing a inner join and only returning engagements that have a relation to user.

To return the user data you should do something like this: Engagement.select('tasks.*, users.*').joins(:user) . This way the object will have engagement and user attributes. But that is not the Rails way.

The "correct" way is:

engagements = Engagement.includes(:user)
engagements.first.user # this will return the user data

This way you're getting all engagements and preloading the user data, this way avoiding n + 1 queries ( Eager-loading ) ;)

Try this Engagement.joins(:users)

It should work.

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