Join data from two tables per foreign key - Rails Activerecord

Asked

Viewed 523 times

0

Hi, I have a Model Comment who is a belongs_to of User, and a Model Profile that also is a belongs_to of User.

I can access User data easily through Comment.first.user, for example, but I would like to access Profile through the User, without having to make several queries.

Both profiles and comments have a foreign key user_id. How to make the results of both tables (comments and profiles) come out in the same query? Thanks in advance!

Update

I have the result of the User.find(1) query that would be

id:12 | email: [email protected] | password_digest:....

And I have the result of the query User.find(1). profile, which would be

name: João | lastname: Eduardo | user_id: 12

You can create a result in Activerecord with the union of these two tables?

email: [email protected] | name: João | lastname: Eduardo

The other question, is it possible to do this with . all, instead of . find or . Where ? I’ve done a lot of research on this, tried to use include, and joins and so far I haven’t been able to. I’m supposed to do two things, but I’m not sure.

  • Explain better by adding a code, it’s easier to understand

1 answer

0


In the "User" class you used the has_many :comments and/or has_many :profiles to indicate both sides of the relationship?

This would allow you to take this information from "User" with:

> c = Comment.find(1)
> puts c.user

Even do the reverse to get the data from "Profile" and "Comments":

> u = User.find(1)
> u_profile = u.profiles
> u_comments = u.comments

And to make the relationship between one class via another class signal in the model using the "through":

belongs_to :profiles, through: :users
  • Thank you for the answer, I would actually like to take this data through Comment, something like Comment.find(1).user.profile (which is not possible), create this chain. I can get the user by comment, but not the profile, which is a brother model.

  • In addition to "has_many" and "belongs_to" there is a subject called "through", which defines the relationship between the tables happens from a third. I don’t know if it’s correct, I don’t know how your modeling is, but it would be like putting something like "belongs_to :profiles, through: users".

  • Perfect. That’s what I was missing, thank you! If you can later update your post with this through. In my problem I could also use the eager_load method that decreases the number of queries @users = User.eager_load(:profile).all

Browser other questions tagged

You are not signed in. Login or sign up in order to post.