Sebastian Zeki
Sebastian Zeki

Reputation: 6874

How to get the results of both tables in a join or include in rails

I have two tables as per the diagram.

I want to write a query that will give me the all the users with their associated relationships. The userid in the Relationship table is now user_id

I have tried

 Relationship.includes(:User)

but this just gives me the results of the Relationship table, as well as

Relationship.joins(:User)

which does the same

enter image description here

There are records in both tables and as you can see from the railroady diagram the associations are correctly set up. What is the correct syntax for this?

Upvotes: 6

Views: 8703

Answers (3)

Vrushali Pawar
Vrushali Pawar

Reputation: 3803

According to the diagram, you should use associations as follows:

User.rb

has_many :relationships

Relationship.rb

belongs_to :user

You can access it by using

User.eager_load(:relationships ).select('users.* , relationships.*')

It will select records from both the table.

Upvotes: 2

Amit Sharma
Amit Sharma

Reputation: 3477

You can try this.

User.joins("INNER JOIN relationships ON users.id = relationships.userid").select("users.id, users.name, relationships.useeid, relationships.followsid")

OR

User.joins("INNER JOIN relationships ON users.id = relationships.userid").select("users.*, relationships.*")

To convert the result into json you can try following.

result = User.joins("INNER JOIN relationships ON users.id = relationships.userid").select("users.*, relationships.*")

result = result.to_json

Upvotes: 4

mtkcs
mtkcs

Reputation: 1716

If you want to eager load users with their realtionships, you can use something like:

user.rb

has_many :relationships

relationship.rb

belongs_to :user

How to use it.

User.includes(:relationships)

edit

as @user123 suggested you can force the eager loading by

User.eager_load(:relationships)

Upvotes: 0

Related Questions