Ruby

Ruby

Made by DeepSource

Renamed column accessed from ActiveRecord model RB-E1012

Bug risk
Major

The rename_column/t.rename migration method in Rails is used to rename a column in a database table. However, if an ActiveRecord model is still accessing the renamed column using its old name, it can lead to errors during runtime.

Renaming a column in a database table using a migration indicates that the column's name has been changed. Therefore, any references to the renamed column in the corresponding ActiveRecord model should be updated as well.

Bad practice

# db/migrate/20230801182839_rename_lastname_to_surname_in_users.rb
class RenameLastnameToSurnameInUsers < ActiveRecord::Migration[6.0]
  def change
    rename_column :users, :last_name, :surname
  end
end

# app/models/user.rb
class User < ApplicationRecord
  def full_name
    "#{first_name} #{last_name}" # This will raise a NoMethodError after the column is renamed
  end
end

Recommended

class User < ApplicationRecord
  def full_name
    "#{first_name} #{surname}"
  end
end

References

  1. ActiveRecord API reference