class Medhospital < ActiveRecord::Base
belongs_to :pcp
belongs_to :hospital
validates_uniqueness_of :pcp_id, :scope => :hospital_id
end
class Pcp < ActiveRecord::Base
has_many :scheds
has_many :medhospitals, dependent: :destroy
has_many :hospitals, through: :medhospitals
has_many :patients, through: :scheds
accepts_nested_attributes_for :medhospitals, reject_if: :all_blank, allow_destroy: true
end
class Hospital < ActiveRecord::Base
has_many :scheds
has_many :medhospitals
has_many :pcps, through: :medhospitals
end
Here is the code you ask Colin:
simple_form_for @pcp do |f|
= f.error_notification
.form-inputs.row.col-md-12
= f.input :name
= f.input :last
= f.input :phone1
= f.input :phone2
= f.input :bod
= f.input :esp
=f.simple_fields_for :medhospitals do |hospital|
= render 'medhospital_fields' , f: hospital, hindex: hcnt
= link_to_add_association 'Add a hospital', f, :medhospitals
.form-actions
= f.button :submit
.nested-fields.hosplital-fields
= f.association :hospital ,label: "Hosplital", collection: Hospital.all, label_method: :name, prompt: "Select Hospital"
= link_to_remove_association "Remove", f
That is all I have, The controller have nothing special all is basic and default. Well not quite, I am using
cocoon gem for the nested forms but other than that is pretty vanilla.
Thanks.
class PcpsController < ApplicationController
before_action :set_pcp, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
def new
@pcp = Pcp.new
end
def create
@pcp = Pcp.new(pcp_params)
respond_to do |format|
if @pcp.save
format.html { redirect_to @pcp, notice: 'Pcp was successfully created.' }
format.json { render :show, status: :created, location: @pcp }
else
format.html { render :new }
format.json { render json: @pcp.errors, status: :unprocessable_entity }
end
end
end
end