0
votes

I want to add another column to model associations see http://guides.rubyonrails.org/v2.3.11/association_basics.html#the-has-many-through-association for example Now i have a new column that also need to check

physicians

id
name
organization_id (new one)

appointments

id
physician_id
patient_id
organization_id (new one)
appointment_date

patients

id
name
organization_id (new one)

My requirements is that if any of the three tables have different organization_id, the association should not work.

in controller, i was using code: @all_patients = Physician.find_by_id_and_organization_id(params[:id], params[:orgId]).patients

to get all patients belong to a physician and show them on UI. In case of some dirty data, tables appointments and patients may have incorrect organization_id. What i want is that the UI should not show the data that organization_id is not the expected one. for example, i have data in db says:

physicians:
1, "Physician 1", 1
2, "Physician 2", 1

appointments
1, 1, 1, 1, 2013-1-1
2, 1, 2, 1, 2013-1-1
3, 1, 3, 1, 2013-1-1
4, 1, 4, 2, 2013-1-1

patients
1, "Patient 1", 1
2, "Patient 2", 2
3, "Patient 3", 1
3, "Patient 4", 1

if i am using Physician.find_by_id_and_organization_id(1,1).patients, i expect to get the following patients
1, "Patient 1", 1
but now i don't know how to config model relations, i got the whole patients data.

So, How to config model?

1

1 Answers

0
votes

You don't need to have a extra column in table appointments. In your appointments model you could just make a extra validation callback and ensure that both patient and physician belong to the same organization:

class Appointment < ActiveRecord::Base
   validate :have_to_be_in_the_same_organization

   def have_to_be_in_the_same_organization
      unless Patient.find(patient_id).organization_id == Physician.find(physician_id).organization_id
          errors.add(:base, "The physician and the patient must be in the same organization to create an appointment!")
      end
   end
end

Solution 2:

If you don't want it to render any error, rather you want to redirect it to somewhere without trying to create that appointment you could do a before filter on your create action in the appointmentscontroller:

class AppointmentsController < ActiveRecord::Base
before_filter :have_to_be_in_the_same_organization, :only => [:create]

  def have_to_be_in_the_same_organization
              unless Patient.find(params[:patient_id]).organization_id == Physician.find(params[:physician_id]).organization_id
                  redirect_to somewhere_path
              end
  end
end