1

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

5
  • what sql doesn't it produce? Commented Jan 20, 2016 at 15:37
  • Do you recieve an error message? If so can you share? Commented Jan 20, 2016 at 15:37
  • 5
    Just a comment, Rails uses inner join by default, so you could do Engagement.joins(:user) Commented Jan 20, 2016 at 15:47
  • He thanks for prompt replies, I not getting any error messages from the query but the issue is I am also not getting the users information. Commented Jan 21, 2016 at 4:53
  • @marcelo the query you mentioned is also fetching me the same result. Thanka fro suggestions anyway Commented Jan 21, 2016 at 4:53

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

The problem with includes way is it will do another query with an IN clause on the associated table. But take a scenario where we just want to fetch one row from the DB and want to get all associations via an inner join. If we do includes there, it will anyway do separate queries for each association. In that case, should we do the first way you described?
0

Try this Engagement.joins(:users)

It should work.

1 Comment

@giovani above query is also not fetching the user data. It is giving me the same result which the query I mentioned in the question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.