Ruby on rails 如果用户有当天的记录,则可以选择列出用户和关联

Ruby on rails 如果用户有当天的记录,则可以选择列出用户和关联,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我有一个用户模型和另一个模型,告诉我他们“签入”工作的时间 因此,在我的用户模型中,我有: class User < ApplicationRecord has_many :checkins end 我想我基本上要执行一个外连接 select * from users u outer join checkins c on u.id = c.user_id where c.created_at = '2017-10-21' 用户当天可能有签入,也可能没有签入,如果有,签入关联应为

我有一个用户模型和另一个模型,告诉我他们“签入”工作的时间

因此,在我的用户模型中,我有:

class User < ApplicationRecord
  has_many :checkins
end
我想我基本上要执行一个外连接

select *
from users u
  outer join checkins c on u.id = c.user_id
where c.created_at = '2017-10-21'
用户当天可能有签入,也可能没有签入,如果有,签入关联应为非nil,否则为nil


如何使用active record执行此查询?

这并不是您要问的问题,但您可以通过作用域关联完成类似的任务。将此添加到您的
用户
型号:

has_many :todays_checkins, class_name: 'Checkin',
  -> { where(created_at: Time.now.beginning_of_day..Time.now.end_of_day) }
def self.find_todays_checkins
  User.has_many :checkins,
    -> { where created_at: Time.now.beginning_of_day..Time.now.end_of_day }
end
对用户记录调用
todays\u checkins
将返回当天的相关签入。例如:

User.first.todays_checkins   # User's checkins for today or nil
您可以遍历所有用户并输出今天的签入,如下所示:

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

如果希望能够动态执行此操作,可以通过向
User
model添加class方法动态更改
checkins
关联:

has_many :todays_checkins, class_name: 'Checkin',
  -> { where(created_at: Time.now.beginning_of_day..Time.now.end_of_day) }
def self.find_todays_checkins
  User.has_many :checkins,
    -> { where created_at: Time.now.beginning_of_day..Time.now.end_of_day }
end

现在,运行
User.find_todays_checkins
将修改您的
checkins
关联,以仅显示今天的签入。您必须编写一个类似的脚本,将关联恢复到其原始范围。当然,这会影响整个
用户
类。我不确定如何将其本地化为一个ActiveRecord关联。

这并不是您想要的,但您可以通过范围关联实现类似的功能。将此添加到您的
用户
型号:

has_many :todays_checkins, class_name: 'Checkin',
  -> { where(created_at: Time.now.beginning_of_day..Time.now.end_of_day) }
def self.find_todays_checkins
  User.has_many :checkins,
    -> { where created_at: Time.now.beginning_of_day..Time.now.end_of_day }
end
对用户记录调用
todays\u checkins
将返回当天的相关签入。例如:

User.first.todays_checkins   # User's checkins for today or nil
您可以遍历所有用户并输出今天的签入,如下所示:

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

如果希望能够动态执行此操作,可以通过向
User
model添加class方法动态更改
checkins
关联:

has_many :todays_checkins, class_name: 'Checkin',
  -> { where(created_at: Time.now.beginning_of_day..Time.now.end_of_day) }
def self.find_todays_checkins
  User.has_many :checkins,
    -> { where created_at: Time.now.beginning_of_day..Time.now.end_of_day }
end

现在,运行
User.find_todays_checkins
将修改您的
checkins
关联,以仅显示今天的签入。您必须编写一个类似的脚本,将关联恢复到其原始范围。当然,这会影响整个
用户
类。我不知道如何将这个问题本地化到一个ActiveRecord协会。

你在这方面有着惊人的声誉,这告诉我们你只能回答这样的问题。为什么?这太基本了。看在名字的份上???你的可能复制品有惊人的声誉,所以这告诉我们你只能回答这样的问题。为什么?这太基本了。为了名字的缘故???可能重复的