Your pattern is pretty lame, but nonetheless you'll want to do one of the following:
- Set the "primary key" as
idUser
- Pull the
idUser
and "increment" it manually
- Use
UUID
functionality
1 - In your DB, you can set your primary_key
to idUser
, which should allow you to provide auto-increment functionality:
$ rails g migration AddPrimaryKey
# db/migrate/add_primary_key______.rb
class AddPrimaryKey < ActiveRecord::Migration
def self.up
execute "ALTER TABLE users modify `idUser` id int(8) AUTO_INCREMENT"
execute "ALTER TABLE users ADD PRIMARY KEY (idUser);"
end
def self.down
execute "ALTER TABLE users modify `idUser` id int(8)"
end
end
$ rake db:migrate
Some wise advice from this answer:
Use the built-in id
field as the primary key. If you're going to use Rails, you should build your app the "Rails way" unless you have very good reason not to.
--
2 - You could use this answer:
#app/models/user.rb
class User < ActiveRecord::Base
before_create :set_id, if: "idUser.blank?"
private
def set_id
self[:idUser] = User.maximum(:idUser).next
end
end
--
3 - If you wanted to use the inbuilt uuid
functionality of Rails, you'd be able to set the idUser
as the primary key (above), but instead of making it auto-increment, make it a string and add a UUID
generator to it:
# db/migrate/add_primary_key______.rb
class AddPrimaryKey < ActiveRecord::Migration
def self.up
execute "ALTER TABLE users ADD PRIMARY KEY (idUser);"
if Rails.env.staging? #-> Heroku PGSQL
execute("CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\"")
else #-> MYSQL
execute("DROP TRIGGER IF EXISTS before_insert_users;");
execute("CREATE TRIGGER before_insert_nodes BEFORE INSERT ON users FOR EACH ROW SET new.uuid = uuid();")
end
end
end
#app/models/user.rb
class User < ActiveRecord::Base
set_primary_key "idUser"
end
This will allow you to just use rails as if you were using an id
/ uuid
column, ActiveRecord
referencing idUser
as required.