Validate uniqueness of association not working.

Hi!

I have the following classes for postgres rails 4 project :

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

``

I am forcing the error to test and the validation for the uniqueness it is not working instead I get this exception:

PG::UniqueViolation - ERROR: duplicate key value violates unique constraint “index_medhospitals_on_pcp_id_and_hospital_id”

BTW I am testing manually from a view form.

Am I doing something wrong ?

Thanks

-Luis

Show us the code are you using to save it.

Colin

Here is the code you ask Colin:

_form

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

``

_medhopital_fields:

.nested-fields.hosplital-fields
= f.association :hospital ,label: “Hosplital”, collection: Hospital.all, label_method: :name, prompt: “Select Hospital”
= link_to_remove_association “Remove”, f

``

I don't see any code there that saves a record.

Colin

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

``

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.

Please quote the previous message when replying, it makes it easier to
follow the thread. Thanks.

Does your medhospital unit test, that checks the validation, pass ok?

Colin

There is no unit test for this.

There is no unit test for this.

Then the solution is obvious. Write one.

Colin