I am completely lost with this. I have a Rails application in which users can create a new provider for use on the system. This provider must have a unique name. Thus, we have a unique index in the database for this field, as shown below:
create_table "vendors", force: :cascade do |t| t.string "vendor_name", limit: 80, null: false t.datetime "updated_at", null: false end add_index "vendors", ["vendor_name"], name: "vendor_name_UNIQUE", unique: true, using: :btree
My problem is that for some reason, Rails validation does not work with this, so the application throws an exception because the database query fails. An exception is the following:
ActiveRecord::RecordNotUnique in VendorsController#create Mysql2::Error: Duplicate entry '3 logiq' for key 'vendor_name_UNIQUE': INSERT INTO `vendors` (`vendor_name`, `updated_at`) VALUES ('3 logiq', '2015-12-03 21:14:12')
The validation of Rails in the vendor.rb model file is as follows:
validates :vendor_name, presence: true, uniqueness: true, length: { minimum: 5, maximum: 80 }
I know that validation is done because I am still getting form errors to check for length and presence. I donβt know what I can do at this moment. Did I miss something?
Below is the code of my seller:
def create @vendor = Vendor.new(vendor_params) @vendor.comments.build(user_comment: comment_params[:new_comment], system_note: 'Created Vendor', user: current_user, user_agent: request.user_agent, resolution: comment_params[:screen_resolution]) respond_to do |format| if @vendor.save format.html { redirect_to vendors_path, notice: 'Vendor was successfully created.' } format.json { render :show, status: :created, location: @vendor } else format.html { @new_item = true; render :new } format.json { render json: @vendor.errors, status: :unprocessable_entity } end end end
Supplier form form code:
<% if @vendor.errors.any? %> <div> <div class="alert alert-danger" role="alert" id="error_explanation"> <h4><strong><%= pluralize(@vendor.errors.count, "error") %></strong> prohibited this vendor from being saved:</h4> <ul> <% @vendor.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> </div> <% end %>