What’s does the [5.0] in Rails 5’s ActiveRecord::Migration mean?
Asked Answered
C

3

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.

Confirmed answered 9/2, 2016 at 21:6 Comment(0)
C
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.

Confirmed answered 9/2, 2016 at 21:6 Comment(1)
Rails 5.0 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.0Jarred
G
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).

Gherlein answered 12/9, 2016 at 19:15 Comment(0)
R
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.

Roseola answered 3/8, 2022 at 17:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.