1

Let's take the example from the association documentation:

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

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

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, through: :appointments
end

My question is, supposing the Appointment model has an appointment_date field how can I set it most elegantly when working with new physicians and patients?

For now my solution for creation is, that instead of using:

physician = Physician.new(...)
patient = Patient.new(...)
physician.patients < patient
physician.save

I use:

physician = Physician.new(...)
patient = Patient.new(...)
appointment = Appointment.new
appointment.physician = physician
appointment.patient = patient
appointment.appointment_date = Time.now
appointment.save

And for querying I found the following solution.

Is there a shorter / more succinct / "Rails" way?

Community
  • 1
  • 1
janosrusiczki
  • 1,920
  • 2
  • 20
  • 41
  • In the meantime I also found [this](http://stackoverflow.com/a/11039314/179570). – janosrusiczki Sep 06 '13 at 04:38
  • do you want any more refactor? – Rajarshi Das Sep 06 '13 at 04:47
  • What do you mean? I detailed what I want as best as I could in the question itself. – janosrusiczki Sep 06 '13 at 05:05
  • I think the solutions you found are "Rails" ways, `patient.appointments.create(appointment_date: Time.now, physician: physician)` may be a little more, but it is almost the same:) The next step is encapsulate the logic in the model, and make the call in one line, it's a personal option..... – Bigxiang Sep 06 '13 at 05:34

0 Answers0