I'm trying to figure out a problem I seem to keep having in setting up polymorphic associations in my Rails 4 app.
I have a project model and an address model. The associations are:
Profile
has_many :addresses, as: :addressable
accepts_nested_attributes_for :addresses, reject_if: :all_blank, allow_destroy: true
Address
belongs_to :addressable, :polymorphic => true
I previously asked this question on the same problem. I couldn't (and still can't) understand the answers in that post: Rails 4 - Polymorphic associations
This time around - I'm having a problem that is triggered when I try to update a profile by inserting an address. The error message identifies the problem as coming from the update action in the profiles controller. The update action has:
My profiles controller update action has:
def update
# successful = @profile.update(profile_params)
# Rails.logger.info "xxxxxxxxxxxxx"
# Rails.logger.info successful.inspect
# user=@profile.user
# user.update.avatar
# Rails.logger.info "prof xxxxxxxxxxxxx"
# Rails.logger.info @profile.update(profile_params)
respond_to do |format|
if @profile.update(profile_params)
format.html { redirect_to @profile }
format.json { render :show, status: :ok, location: @profile }
else
format.html { render :edit }
format.json { render json: @profile.errors, status: :unprocessable_entity }
end
end
end
The error message says:
ERROR: duplicate key value violates unique constraint "index_addresses_on_addressable_type_and_addressable_id"
DETAIL: Key (addressable_type, addressable_id)=(Profile, 1) already exists.
Does anyone know what this message means, and how to address it?
In your database, you have set a unique constraint: , you can go to the database to see what you have set by the name of "index_addresses_on_addressable_type_and_addressable_id". As the error message show, you try to update a record with value ( Profile , 1) which has already been used by another record.
To solve this issue, there are two solutions:
one is from the database side:
you need to know why there is a unique constraint about addresses. if it is not need , you can remove it from the database.
the other is ensure the (addressable_type, addressable_id) is unique before you update your data into database.
hope this can give a kind of help