Restrict PER user in rails request

Thus, I have a standard user structure, with the main key of the key, and what is not, and the following table is personalized :

user_id | persona_id | time_inserted 2 1 x 2 2 x+1 2 3 x+2 1 1 x+3 5 8 x+6 5 9 x+1 

What I need to do is get the LAST string and limit ONE for each user ID. So, in this query, I want:

[2, 3], because the last inserted for 2 was persona_id 3 (x + 2), [1, 1] and [5,8], because the last inserted for 5 was persona_id 8 (x + 6)

This is my request:

 to_return = Persona.select(to_get).where(to_condition) 

This works, but extracts them all. How can I limit the query to query? Thank you very much.

+4
source share
1 answer

This should work:

 to_return = Persona.select(to_get).where(to_condition).group('user_id').having('time_inserted = MAX(time_inserted)') 

Update

You cannot select a column unless you put it in a group clause. If you want to group only user_id , one of the possible solutions is to select user_id first with the maximum time_inserted as follows:

 users_ids_relation = Persona.select('user_id').group('user_id').having('time_inserted = MAX(time_inserted)') 

Then attach it to the personas table based on the condition and then select the columns you want:

 users_ids_relation.joins('personas').where(to_condition).select(to_get) 

This will give you the expected result.

+2
source

All Articles