如何通过first_or_initialize而不是find_or_initialize_by(Rails)使用joins方法?

ree*_*ces 5 ruby join ruby-on-rails inner-join

有没有办法find_or_initialize_by使用该joins方法重写下面当前使用的过程?

对于上下文-我有users(员工)谁attendances在系统中记录他们(a user有很多attendances,并且一条attendance记录属于a user)。

Attendance.find_or_initialize_by(
  user: User.find_by(name: 'Bob'),
  date: Time.zone.today
)
.update(...) # Update some columns after this
Run Code Online (Sandbox Code Playgroud)

我正在尝试.joins像这样重写它:

Attendance.joins(:user)
  .where(users: {name: 'Bob'}, date: Time.zone.today)
  .first_or_initialize
  .update(...) # Update some columns after this
Run Code Online (Sandbox Code Playgroud)

我的测试返回了混合结果:

  • 只需要updated通过记录的测试用例
  • attendance尚不存在该记录的测试用例(例如,当我不得不时initialize)失败

错误消息是 ActiveRecord::RecordInvalid: Validation failed: User must exist。但是我很困惑,因为用户实际上存在-如果我使用进行调试byebug,则用户在那里。

bo-*_*-oz -1

您是否在更新调用中设置 Bob 的 ID?基本上,当您运行此命令并且 where 子句返回空时,会实例化一个空的新记录。此时,所有对Bob的引用都消失了,因此您需要在更新中再次设置它:

Attendance.joins(:user)
  .where(users: {name: 'Bob'}, date: Time.zone.today)
  .first_or_initialize
  .update(user: User.find_by(name: 'Bob'), #other stuff ) # Update some columns after this
Run Code Online (Sandbox Code Playgroud)