Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting initial value for primary key in Rails (i.e. first object's id is 1000 instead of 1)

What's the best way of going about this. Is there something I can put in the migrations? Thanks in advance.

like image 919
Newy Avatar asked Jun 23 '09 13:06

Newy


People also ask

What is ActiveRecord in Ruby on Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

Which command is true to rollback migration in Rails?

You must rollback the migration (for example with bin/rails db:rollback ), edit your migration, and then run bin/rails db:migrate to run the corrected version.

What does where return rails?

where returns an ActiveRecord::Relation (not an array, even though it behaves much like one), which is a collection of model objects. If nothing matches the conditions, it simply returns an empty relation. find (and its related dynamic find_by_columnname methods) returns a single model object.


2 Answers

This is database specific. Just do something like the following in your migration:

class MyMigration < ActiveRecord::Migration
  def self.up
    create_table :my_table do |t|
      # ...
    end
    execute "ALTER TABLE my_table AUTO_INCREMENT = 1000" # for MySQL
  end

  def self.down
    # ...
  end
end

Or indeed, even better, as suggested by Bane:

  def self.up
    create_table :my_table, :options => "AUTO_INCREMENT = 1000" do |t|
      # ...
    end
  end

Be cautious with database-specific migrations, though! Using any SQL that is specific to your database will break compatibility with other databases and is generally not a good idea.

like image 144
molf Avatar answered Sep 27 '22 17:09

molf


Any string passed into the ":options" option will be appended to the end of the SQL statement that creates the table. Best practice.

def self.up
    create_table :my_table, :options => "AUTO_INCREMENT = 1000" do |t|
      # ...
    end
end
like image 22
Barry Gallagher Avatar answered Sep 27 '22 18:09

Barry Gallagher