Reputation: 6874
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
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
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
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
Reputation: 1716
If you want to eager load users with their realtionships, you can use something like:
has_many :relationships
belongs_to :user
How to use it.
User.includes(:relationships)
as @user123 suggested you can force the eager loading by
User.eager_load(:relationships)
Upvotes: 0