1

I have a location table in my rails app which has four columns :-

| Id | Longitude | Latitude | user_id

Now I have an array containing the list of user_ids. How can I write an active record query to select the last row of each user id. For example, if I have three user_ids in my array [1,2,3] I want the query to return just the last row corresponding to each user_id (lets assume entries for each user_id is present in the table) from the table.

So, far I am able to get all the rows corresponding to all the user_ids using this following query:

@ids = [1,2,3]
@locations = Location.where(user_id: ids)

How can I modify this activerecord query so that it returns only the last row corresponding to each user_id

1

2 Answers 2

1

Assuming you have a User model that has many locations, you could start from the user model and use the association to get to your last location for each user.

User.where(:id => @ids).includes(:locations).collect { |u| u.locations.last }
  • User.where(:id => @ids) returns your collection of user objects.
  • includes(:locations) eager loads the associated locations, so we don't run into an n+1 problem.
  • collect { |u| u.locations.last } maps the last associated location into an array
Sign up to request clarification or add additional context in comments.

Comments

0

You can also try this:

@ids = [1,2,3]
@locations = @ids.map {|id| [Location.where(user_id: id).last.location,User.find(id).name]}
#This would give you something like this: [["US",XYZ],["IND","ABC"]]

2 Comments

Doing a little bit of editing like @locations = @ids.map {|id| Location.where(user_id: id).last} makes this solution work. I want to ask one more thing, how can I add user name corresponding to the user_id (User has_many Locations relationship in the response ?
Please check the updated answer, let me know if it's working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.