1

Using Postgresql 9.1 and Rails 3.2.2. How would I return a collection of the last single users_checkins per venue for a given user?

I have tried

User.find(1)
  .users_checkins
  .joins(:venues_checkins)
  .merge(VenuesCheckin.select('DISTINCT(venues_checkins.venue_id)')) 

but that does not retrieve any of the attributes for the UsersCheckin. My models are below.

class Venue
  has_many :venues_checkins
  has_many :users_checkins, through: :venues_checkins
end

class UsersCheckin
  #start:datetime
  #finish:datetime
  belongs_to :user
  belongs_to :venues_checkin
end

class VenuesCheckin
  belongs_to :venue
  has_many :users_checkins
end

class User
  has_many :users_checkins
  has_many :venues_checkins, through: :users_checkins
  has_many :venues, through: :users_checkins
end

Update

If a user has 3 users_checkins records for Venue A and 3 for Venue B, my collection should return 2 records with one record being the last created users_checkin from Venue A and the other record being the last created users_checkin from Venue B with the collection ordered by first record in the collection being which of those 2 records was created last. And I start with the user because I only want the users_checkins for the given user.

2
  • If you want the end result to be a collection of UsersCheckin then should that be your starting point? Could you clarify what you mean by "last single users_checkins per venue"? Commented Mar 5, 2012 at 20:54
  • If a user has 3 users_checkins records for Venue A and 3 for Venue B, my collection should return 2 records with one record being the last created users_checkin from Venue A and the other record being the last created users_checkin from Venue B with the collection ordered by first record in the collection being which of those 2 records was created last. And I start with the user because I only want the users_checkins for the given user. Commented Mar 5, 2012 at 21:18

1 Answer 1

1

If you can write the SQL and get it to work in the psql prompt, make it into a custom method in the User class, and skip trying to wedge the custom query into the ORM.

Also, it sounds like you want a min/max qualifier in your query, rather than distinct.

Sign up to request clarification or add additional context in comments.

Comments

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.