Ignoring a Rails model attribute

Rmag Breaking News

Imagine that you need to remove an obsolete field from your production database, but you’re not confident that this field is truly unused. How can you proceed safely? If only there were a way to pretend that this field no longer exists, allowing you to check if the application still functions properly without it.

Enter ActiveRecord’s ignored_columns to the rescue!

With this feature, you can instruct ActiveRecord to behave as if a specific database field doesn’t exist. It removes all accessors related to that field from the model and ignores it in database queries.

Let’s take a look at an example:

Suppose you have a model called Person with several attributes, and you want to eliminate the middle_name field:

class Person < ActiveRecord::Base
# Schema:
# id :bigint
# first_name :string, limit: 255
# middle_name :string, limit: 255
# last_name :string, limit: 255
self.ignored_columns += [:middle_name]
end

Comes ActiveRecordignored_columns for the rescue!

With it, you can instruct ActiveRecord to pretend that a specific database field doesn’t exist, removing all accessors from the model and ignoring the field on database queries.

Let’s see an example:

You have the model Person with some attributes and you want to get rid of middle_name.

class Person < ActiveRecord::Base
# schema:
# id :bigint
# first_name :string, limit: 255
# middle_name :string, limit: 255
# last_name :string, limit: 255
self.ignored_columns += [:middle_name]
end

Now, any attempts to access the middle_name attribute will fail. For instance:

person = Person.create!(first_name: “John”)
person.middle_name # => raises NoMethodError

Attention: Keep in mind that this approach won’t prevent direct database calls to fetch this field. The field itself hasn’t been removed from the database; it’s simply ignored by ActiveRecord.

Once you’ve thoroughly tested your application and verified that everything works as expected, you can create a new migration to permanently remove the field from the database.

Happy coding! 😊

Reference: ActiveRecord ignored_columns

Leave a Reply

Your email address will not be published. Required fields are marked *