【问题标题】:Rails- has_many :through create, delete and access recordsRails- has_many:通过创建、删除和访问记录
【发布时间】:2016-02-19 09:37:45
【问题描述】:

以下代码来自http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

class CreateAppointments < ActiveRecord::Migration
 def change
  create_table :physicians do |t|
   t.string :name
   t.timestamps null: false
  end

create_table :patients do |t|
  t.string :name
  t.timestamps null: false
end

create_table :appointments do |t|
  t.belongs_to :physician, index: true
  t.belongs_to :patient, index: true
  t.datetime :appointment_date
  t.timestamps null: false
end

结束 结束

在上面的例子中我是怎么做的:

1) 创建/破坏医生和患者之间的关系。我只是使用:

Create: Appointment.create(physician_id, patient_id)
Destroy: (i have no clue hot to do this)

正确的做法是什么?

2) 我如何访问特定患者或医生的预约模型中的所有预约日期?

【问题讨论】:

  • 我目前正在使用 create 创建关系。至于销毁,我一直在销毁控制台上的记录。 (如果这真的很基本,我对 Rails 很陌生)
  • 我刚刚在另一个问题上找到了以下创建关系:@course.topics
  • 您的代码 sn-p 仅将新主题分配给名为 @course 的临时变量。因此,尽管该主题现在是 @course 的一部分,并且可以通过 @course.topics 访问,但没有持久的关系。

标签: ruby-on-rails


【解决方案1】:

1/

 Appointment.find_by(physician: @physician, patient: @patient).destroy

2/

 @patient.appointments.pluck(:appointment_date)

【讨论】:

    【解决方案2】:

    您可以根据自己的喜好创建医生或患者的预约:

    @patient = Patient.find(params[:id])
    @patient.appointments.create(physician: *object*, appointment_date: *datetime object*)  # auto sets the patient to match the @patient.id
    
    #or from the physician
    @physician = Physician.last #select the last physician
    @physician.appointments.create(patient: *object*, appointment_date: *datetime object*) # auto sets the physician to match the @physician.id
    

    如果你有两个 ID,你也可以这样创建:

    Appointment.new(patient: *Patient object*, physician: *Physician object*, appointment_date: *datetime object*)
    

    要销毁记录,只需找到活动记录对象并对其调用destroy即可。在控制台中玩耍,看看它是如何工作的。例如:

    Patient.find(id).appointments.last.destroy #destroys the last appointment for a patient with id
    

    或直接查找并删除约会:

    # find active record and then call destroy
    @appointment = Appointment.find(1) # find appointment with ID: 1
    @appointment.destroy
    
    #call destroy directly by chaining commands
    Appointment.find(1).destroy #does the exact same thing as above.
    

    【讨论】:

    • 谢谢。如果我想破坏一个特定的关系,我可以使用@Statyx 的方法:@patient.appointments.pluck(:appointment_date) 还是你有不同的方法?
    • pluck 不是销毁记录的方法。它获取特定字段。看看我的最后一行代码。只需确保您有对要删除的 ActiveRecord 的引用并在其上调用 destroy 方法即可。我会在我的回答中澄清。
    • 完美!你们俩都是救命稻草!
    猜你喜欢
    • 2020-11-20
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-20
    • 2015-03-23
    • 1970-01-01
    • 2016-04-22
    相关资源
    最近更新 更多