0

I am using rails and SQL server in a project. When I put the following validation in the model: validates :Clave, uniqueness: true I get this error: can't cast ActiveRecord::ConnectionAdapters::SQLServer::Type::Char::Data to varchar

this is my schema.rb

create_table "Productos", primary_key: "Clave", force: :cascade do |t|
    t.integer  "Id",                 limit: 4,                             null: false
    t.varchar  "Producto",           limit: 255
    t.varchar  "CodBarras",          limit: 50
    t.varchar  "IdEmpresa",          limit: 50

  end

this is my model producto.rb

class Producto < ActiveRecord::Base
  self.primary_key = "Clave"

  validates :IdEmpresa, uniqueness: true
  validates :Clave, uniqueness: true
  validates :Producto, presence: true

end
LuisC
  • 335
  • 1
  • 11

1 Answers1

0

I don't think you can or need to validate primary keys. Entries without keys are not persisted in the database. Saving a new object should generate a new primary key for it.

Take a look at these posts for chaning the primary key to not be an integer:

Community
  • 1
  • 1
HarlemSquirrel
  • 8,966
  • 5
  • 34
  • 34
  • Thanks for replying, I need to validate it because when an existing primary key is inserted it shows me the red screen of rails error indicating that it exists. However if I validate it this way, I can show the errors to the user in a better way like this: <% errors.full_messages.each do | message | %>
  • <% = message%> li> <% End%>
  • – LuisC Jan 28 '17 at 15:33
  • Are you trying to set the primary key based on user input? – HarlemSquirrel Jan 28 '17 at 15:37
  • You don't want to do that. ActiveRecord will generate the primary key for you. User input should not be used to set primary keys. Just make that user input a new column and use the default primary key `id` – HarlemSquirrel Jan 28 '17 at 15:45
  • I know but I am working on a previously developed project and it was previously established because the field "Clave" is like an identifier for the products – LuisC Jan 28 '17 at 17:04
  • I have the same error when validating another field that is string. Apparently when you make a validates: product, uniqueness: true I get that error – LuisC Jan 28 '17 at 18:39
  • What does your schema.rb and model look like? – HarlemSquirrel Jan 28 '17 at 18:43
  • I have updated my post with the schema and mode. I get the same error with the field "CompanyId", because it's string – LuisC Jan 28 '17 at 18:53