Join data from two tables by foreign key - Rails ActiveRecord

0
Hello, I have a Model Comment which is a belongs_to of User , and a Model Profile that is also a belongs_to of User .

I can easily access User data through Comment.first.user , for example, but I'd like to access Profile through User , without having to do multiple Queries.

Both profiles and comments have a foreign key user_id . How can I make the results of both tables (comments and profiles) come out in the same query? Thank you!

Update

I have the result of the query User.find (1) 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

How can I create a result in ActiveRecord by joining these two tables?

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

The other question, can you do this with .all, instead of .find or .where? I've been researching a lot about this, I've tried using include, and joins and so far I have not been able to. I suppose I have to do two queries, but I'm not sure.

    
asked by anonymous 26.03.2018 / 04:44

1 answer

0

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

This would allow you to get this "User" information with:

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

To do the inverse to get the data of "Profile" and "Comments":

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

And to make the relationship between a class via another class signalize in the model using the "through":

belongs_to :profiles, through: :users
    
26.03.2018 / 05:24