How to get related data in Ruby on Rails?

Asked

Viewed 363 times

1

Hello. I have an app where User has_many Status. And Status has_many Likes.

How do I get the total amount of Ikes a user has? For example, it has 2 status with 10 Ikes each, which gives a total of 20 Ikes. How I take this amount?

My model is simple:

User has_many Status

Status has_many Likes

1 answer

1


Use has_many through:

class User
  has_many statuses
  has_many likes, through: :statuses
end

The word through means "through", so the above instruction means "has many Likes through statuses".

Both calls will be available:

@user.statuses
@user.likes

In the second case, Activerecord will take charge of doing the INNER JOIN.

Some darlings:

@user.likes                  # Todos os likes do usuário
@user.statuses.find(1).likes # Todos os likes do status de id=1, que pertence ao usuário
@user.statuses.first.likes   # Primeiro
@user.statuses.last.likes    # Último
                             # etc

Be sure to read Active Record Query Interface.

  • Thank you very much, once again Andrey. Just one question: In this case, I could not get how many Ikes the user gave right? Ex: If I put only user has many likes and put @user.likes he would give me all the sent likes. When I use the through he gives me all the received by Status. Would there be any way to get the 2? Maybe name different?

  • @Igormartins I edited the question by adding some darlings. That’s what you want?

Browser other questions tagged

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