开发者

Ruby on Rails Find Where No Record

开发者 https://www.devze.com 2023-03-28 02:43 出处:网络
I have the following associations: Outlet => has_many :checkins Checkin => belongs_to :outlet Every day, and Outlet needs to get 1 checkin.

I have the following associations:

Outlet => has_many :checkins
Checkin => belongs_to :outlet

Every day, and Outlet needs to get 1 checkin. I can get the list of outlets with a checkin made today with this:

Checkin.where('DATE(created_at) = ?', Date.Today)

However, I am not sure about how I could get a list of outlets that have not had a checkin associated with them today.

So if Outlet A had a check in record created today, but Outlet B had not had a check in, and hence no record made, Outlet B would be returned.

If we say that:

@checkin_outlet_name = Checkin.where('DATE(created_at) = ?', Date.Today).outlet.name

@outlet = Outlet.all

I would theoretically be able to find all the Outlets without checkins made today, because all the records that are in @outlet and NOT on @checkin_outlet_name would be the ones I am looking for.

However, I have no idea h开发者_开发问答ow to achieve this in Rails.

Any help would be greatly appreciated.


You probably want something like Outlet.joins(:checkins).where("DATE(checkins.created_at) <> ?", Date.today)


If you want to do it without writing complex queries,

class Outlet
  scope :checked_in_today, { joins(:checkins).where("DATE(checkins.created_at) = ?", Date.today) }
end

# remove items from Outlet.all which have been checked in today (Array - Array)
@not_checked_in_today = Outlet.all - Outlet.checked_in_today

Better way to do it in DB

class Outlet
  scope :not_checked_in_today, lambda {
    joins("LEFT OUTER JOIN (SELECT * FROM checkins WHERE created_at = #{Date.today.to_s(:db)}) c ON outltes.id = c.outlet_id"). #only select checkins created today
    where("c.outlet_id IS NULL"). # only keep outlets not checked in today
    select("DISTINCT outlets.*") # remove duplicates 
  }
end

@not_checked_in_today = Outlet.not_checked_in_today
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号