How to get related data in Ruby on Rails?

1

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

How do I get the total likes a user has? For example, it has 2 statuses with 10 likes each, which gives a total of 20 likes. How do I get this value?

My model is simple:

User has_many Status

Status has_many Likes

    
asked by anonymous 20.08.2014 / 00:52

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 statement means "have many likes through statuses."

Both calls will be available:

@user.statuses
@user.likes

In the second case, ActiveRecord will take care of INNER JOIN .

Some queries :

@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 .

    
20.08.2014 / 03:13