3
votes

When creating an appointment, for let say Organization 'ABC', I can also see physicians that belongs to other organization. It suppose to only list physician from 'ABC' and not others. How should I go about this.

Thank you.

My Appointment form:

<%= simple_form_for(@appointment, :html => { :class => 'form-horizontal' }) do |f| %>
  <div class="form-inputs">
    <%= f.hidden_field :patient_id %>
    <%= f.association :physician, :label_method => :first_name, :include_blank => false, :as => :radio_buttons, :required => true %>
    <%= f.hidden_field :appointment_date, :value => DateTime.now  %>
    <%= f.hidden_field :organization_id, :value => current_user.organization_id%>
  </div>

  <div class="form-actions">
    <%= f.button :submit, "Create Appointment" %>
  </div>
<% end %>

My models:

/app/models/physician.rb

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

  attr_accessible :physician_name, :organization_id
end

/app/models/appointment.rb

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

  attr_accessible :physician_id, :patient_id, :appointment_date, :state, :organization_id
end

/app/models/patient.rb

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, :through => :appointments
  belongs_to :organization

  attr_accessible :patient_name, :organization_id
end

My Controllers:

/app/controllers/appointment_controller.rb

class AppointmentsController < ApplicationController
  def new
    @appointment = Appointment.new
    @appointment.patient_id = params[:patient_id]
  end

  def create
    @appointment = Appointment.new(params[:appointment])

    if @appointment.save
      flash[:notice] = "New appointment record created"
      redirect_to dashboards_path
    else
      render 'new'
    end
  end
end
1

1 Answers

7
votes

This is because simple_form does not know about your scopes. If you tell it:

<%= f.association :phyisician %>

it will simply list all available physicians in the database.

The solution is to give it the collection of physicians you want to show, for example you could write:

<%= f.association :physician,
                  :collection => @appointment.patient.organization.physicians,
                  :label_method => :first_name,
                  :include_blank => false,
                  :as => :radio_buttons,
                  :required => true %>