【问题标题】:How to update has_many :through table?如何更新 has_many :through 表?
【发布时间】:2017-07-14 00:19:53
【问题描述】:

这是我之前的一个问题的后续问题:How to Model doctor and patient relation 我对rails相当陌生,我正在病人和医生之间进行预约系统,我已经建立了关系,使用设计设置了身份验证。我有 3 个模型:

class Doctor < ApplicationRecord
  has_many :appointments
  has_many :patients, through: :appointments
end

class Patient < ApplicationRecord
  has_many :appointments
  has_many :doctors, through:appointments
end

class Appointment < ApplicationRecord
  #table_columns: id | start_time| end_time| doctor_id| patient_id|slot_taken|
  belongs_to :patient
  belongs_to :doctor
end

我已经创建了约会控制器:一些操作如下:

#current_doctor comes from devise. Have created two separate models for doctor and patients using devise

def create
  @appointment = current_doctor.appointments.build(appointment_params) 
  respond_to do |format|
    if @appointment.save
      format.html { redirect_to appointments_path, notice: 'Appointment was successfully created.' }
    else
      format.html { render :new } 
    end
  end
end

def update
  respond_to do |format|
    if @appointment.update(appointment_params)
      format.html { redirect_to appointments_path, notice: 'Appointment was successfully updated.' }
    else
      format.html { render :edit } 
    end
  end
end

private
  def appointment_params
    params.require(:meeting).permit(start_time, end_time)
  end

如您所见,医生可以创建他/她有空的时间段,并且可以为他/她自己编辑、更新和销毁这些时间段,当他创建一个时隙时,预约表会更新为医生 ID、开始时间和结束时间.

现在,我应该怎么做才能添加 patient_id 并将 slot_taken 更改为 true(默认值:false)?当患者预订可用时隙时,约会表应使用 Patient_id 和 slot_taken 值进行更新。我应该如何更新约会表,我应该把代码放在哪里?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 ruby-on-rails-5


    【解决方案1】:

    首先,一些建议:我认为两个用户模型不是一个好主意。认为最好有一个User 设计模型,并且该用户有一个与之关联的Role,因此您可以控制访问类型。如果您必须向该系统添加更多类型的用户,为每个用户创建一个模型可能会很麻烦。

    关于预约,问题,大致上,如果您有一个doctor 实例,并且您想在s start_time 和e end_time 为某个患者预约,您可以执行以下操作:

    doctor.appointments.find_by(start_time: s, end_time: e).update(patient_id: your_patient_id)
    

    关于把它放在哪里,取决于你的系统是如何工作的。是指派自己的客户吗?或者某些管理员会这样做? 无论如何,认为你应该有另一个动作/视图来完成那个任务,所以你可以有一个用户可以输入该信息的表单,当他发送表单时,你处理它并以某种方式进行更新,就像之前展示的那样.

    希望对你有帮助,祝你好运

    【讨论】:

    • 例如,假设医生 A 在那里,他创建了 7 月 13 日上午 8:00 到上午 09:00 的可用时间段。现在在患者方面,患者可以看到医生 A 在 7 月 13 日上午 8:00 至上午 09:00 有空。他点击书本按钮,并且耐心_id 应该得到更新。我正在使用 book 按钮传递医生 ID。现在,我的问题是我应该将它传递给约会表中的相同更新方法吗?
    • 您可以重复使用该更新方法。由于我相信您提供给患者的表格已经包含了医生 ID、开始时间和结束时间信息(您之前有这些信息),您需要获取的唯一信息是患者 ID 信息,您可以在更新方法中获取这些信息,由 current_user(在您的情况下为 current_patient)
    • 好的,谢谢。现在可以了。我不知道更新方法是否应该像那样访问是否是一种好习惯。我也将按照您的建议更改为一种模型。
    • 我同意这一点。使用两种不同的模型来大规模管理一个应用程序,这些模型服务于相同的目的,这成为一场噩梦,最终只会产生技术债务。 ;)
    猜你喜欢
    • 1970-01-01
    • 2010-09-20
    • 2013-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 2016-01-20
    • 2015-11-27
    相关资源
    最近更新 更多