在ActiveRecord中,可以使用以下代码来选取用户最近约会的ID:
class User < ActiveRecord::Base
has_many :appointments
def latest_appointment_id
appointments.order(created_at: :desc).limit(1).pluck(:id).first
end
end
在上述代码中,假设用户模型为User,约会模型为Appointment,并且在用户模型中定义了与约会模型的关联关系。
latest_appointment_id方法使用了ActiveRecord的查询方法,首先根据约会创建时间(created_at)降序排列约会记录,然后使用limit(1)方法限制只返回一条记录,最后使用pluck(:id)方法提取约会记录的ID值,并通过first方法获取第一个ID值。
这样,通过调用latest_appointment_id方法,即可获取用户最近约会的ID。