简体   繁体   English

如何操作has_many上的数据:通过Ruby on Rails上的ActiveRecords上的关联?

[英]How can I manipulate data on a has_many :through Association on ActiveRecords on Ruby on Rails?

The documentation is a little poor in this aspect. 文档在这方面有点差。 If I have this tables 如果我有这个表

 Physicians Table
-----------
id integer
name string

Appointments table
----------------
id integer
physician_id integer
patient_id integer
appointment_date datetime

Patients table
---------------
id integer
name string 

and this models: 这个型号:

class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, :through => :appointments
end

class Appointment < ActiveRecord::Base
  belongs_to :pshysician
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :pshysicians, :through => :appointments
end

how do I do to insert an appointment on the database? 如何在数据库中插入约会? It's not clear at all in the Rails webpage 在Rails网页中根本不清楚

This is a quite broad question actually. 实际上,这是一个相当广泛的问题。 To insert a record in the database you can do one of three things. 要在数据库中插入记录,您可以执行以下三种操作之一。

  1. Appointment.create(patient_id: 1, physician_id: 1, apt_date: DateTime.now)

  2. If you have an instance of the Patient model lets call it patient and you want to assign in to physician with id=2 then 如果你有一个Patient模型的实例,我可以称之为patient然后你想分配给id=2医生

    patient.appointments.create(physician_id: 2, apt_date: DateTime.now)

  3. If you have an instance of the Physician model called physician then 如果您有一个名为physicianPhysician模型实例

    physician.appointments.create(patient_id: 10, apt_date: DateTime.now)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Ruby on Rails-通过关联访问:has_many =&gt;中的数据 - Ruby on Rails - Accessing data in :has_many => :through association 如何将记录添加到has_many:通过Ruby on Rails中的关联 - how to add records to has_many :through association in Ruby on rails 如何通过在rails中通过关联对has_many进行关联来实现has_many? - How do I do a has_many through association on a has_many through association in rails? 如何在Ruby on Rails中通过关联订购has_many? - How do I order a has_many through association in Ruby on Rails? 如何通过Rails中的关联通过has_many持久化数据 - How to persist data via has_many through association in rails Rails-has_many:通过关联+保存关联数据 - Rails - has_many :through association + save data for association 如何在Rails 3中搜索has_many关联(meta_where或railslogic?) - How can I search through a has_many association in Rails 3 (meta_where or railslogic?) 如何在Rails 5中模拟“ has_many”关联的“ OR”条件? - How can I simulate `OR` conditions for `has_many` association in Rails 5? Ruby on Rails“ has_many:through”关联返回一个数组 - Ruby on Rails “has_many :through” association return an array Ruby on Rails:使用has_many:through关联进行过滤 - Ruby on Rails : Filter with has_many :through Association
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM