Euler
Euler

Reputation: 652

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

Upvotes: 1

Views: 3658

Answers (2)

Alex Buschle
Alex Buschle

Reputation: 166

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

Upvotes: 3

Giovani Barcelos
Giovani Barcelos

Reputation: 134

Try this Engagement.joins(:users)

It should work.

Upvotes: 0

Related Questions