1

I have a user model and another model that tells me the time they "checked-in" to work.

User
- id
- name

Checkins
- user_id
- timestamps

So in my User model I have this:

class User < ApplicationRecord
  has_many :checkins
end

What I want to do is on a page display a list of users, and IF they have a checkin for the current day then the 'checkin' association should be present, otherwise null.

@users = User.find_todays_checkin()

So I have to basically perform an outer join I guess?

select *
from users u
  outer join checkins c on u.id = c.user_id
where c.created_at = '2017-10-21'

A user may or may not have a checkin for the current day, if they do, the checkin association should be non-nil, otherwise nil.

How can I do this query using active record?

Blankman
  • 259,732
  • 324
  • 769
  • 1,199
  • 1
    U have amazing reputation on SO which tells us you only can answer such question. Why ????? It's so basic. For name sake??? – krishnar Oct 21 '17 at 20:37
  • Possible duplicate of [LEFT OUTER JOIN in Rails 4](https://stackoverflow.com/questions/24358805/left-outer-join-in-rails-4) – krishnar Oct 21 '17 at 20:43

1 Answers1

0

This is not exactly what you are asking, but you could accomplish something similar with a scoped association. Add this to your User model:

has_many :todays_checkins, class_name: 'Checkin',
  -> { where(created_at: Time.now.beginning_of_day..Time.now.end_of_day) }

Calling todays_checkins on a user record will return associated checkins for the current day. For example:

User.first.todays_checkins   # User's checkins for today or nil

You could iterate through all users and output today's checkins as follows:

@users = User.all.includes(:checkins)
@users.each { |user| puts user.todays_checkins }

UPDATE

If you want to be able to do this dynamically, you can change checkins association on the fly by adding a class method to you User model:

def self.find_todays_checkins
  User.has_many :checkins,
    -> { where created_at: Time.now.beginning_of_day..Time.now.end_of_day }
end

Now, running User.find_todays_checkins will modify your checkins association to only show today's checkins. You would have to write a similar revert the association back to its original scope. Of course, this affects the entire User class. I am not quit sure how to localize this to one ActiveRecord association.

Tom Aranda
  • 5,919
  • 11
  • 35
  • 51