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.
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.
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.
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).
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.
© 2022 - 2024 — McMap. All rights reserved.
class MyMigration < ActiveRecord::Migration[5.0]
. Runningbundle show activerecord
returns/Users/username/.rvm/gems/ruby-2.3.0/gems/activerecord-5.0.0
– Jarred