23

A migration I created in a Rails 5 application had 5.0 passed into a method:

class CreateVariableKeys < ActiveRecord::Migration[5.0]
  ...
end

I would like to know what the [5.0] means.

gnerkus
  • 11,357
  • 6
  • 47
  • 71

3 Answers3

18

It is a class method of ActiveRecord::Migration and is defined here.

It allows us to select the version of migrations we wish to use between 4.2 and 5.0. The method throws a:

"Unknown migration version ... "

error if an incompatible version is passed as an argument.

Production ready versions of ActiveRecord don’t have that method so it should go away as soon as Rails 5 goes out of beta.

gnerkus
  • 11,357
  • 6
  • 47
  • 71
  • 6
    [Rails 5.0](http://weblog.rubyonrails.org/releases/) was released 30th June 2016. Creating a migration still displays the version ```class MyMigration < ActiveRecord::Migration[5.0]```. Running ```bundle show activerecord``` returns ```/Users/username/.rvm/gems/ruby-2.3.0/gems/activerecord-5.0.0``` – Luke Schoen Jul 23 '16 at 23:20
7

This blog has more info too

It seems to be there so that you don't have to upgrade old migrations, when moving from rails 4 to rails 5. (There are some small changes in the migrations API).

Andrew
  • 2,829
  • 3
  • 22
  • 19
1

In Ruby, you can define a method named [] on a class like so:

class Foo
  def self.[](arg)
    puts arg
  end
end

And call it like this:

Foo["print me"]
--> "print me"

Foo[2.3]
--> 2.3

See this answer for an explanation.

In Rails 7.0, ActiveRecord::Migration[version_number] contains this code (source):

def self.[](version)
  Compatibility.find(version)
end

Where Compatibility::find (source) finds the appropriate version of the migration, which you can verify using rails c:

irb(main):001:0> ActiveRecord::Migration[5.2]
=> ActiveRecord::Migration::Compatibility::V5_2

Hope that helps.

Greg
  • 55
  • 1
  • 7