user1175969
user1175969

Reputation: 570

Creating has_many :through Association conditionally

I have the following classes:

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

I want only a Physician to be able to create an Appointment, but not a Patient. Please let me know how I can have this restriction at the Model level.

Thanks!

Upvotes: 0

Views: 61

Answers (1)

Jorge de los Santos
Jorge de los Santos

Reputation: 4633

You don't need to use the association to retrieve patients appointmets. Just create a getter method for them:

class Patient < ActiveRecord::Base
  def appointments
    Appointment.where(patient_id: self.id)
  end
end

Upvotes: 2

Related Questions