Search code examples
ruby-on-railsrubyactiverecordruby-on-rails-5.2

Deal with a column name 'hash' in a legacy database


I have to access a legacy database from within a Rails 5.2 project. Unfortunately I can not change any table column names and the table contains a column with the name hash which doesn't work with ActiveRecord (is will throw an error because of hash which is an existing method). I don't need that column but I can neither rename nor delete it either.

Is there a way to tell ActiveRecord to not use the hash field of a given table?


Solution

  • You can use the ignored_columns method that was added to Ruby on Rails in version 5.0 to ignore columns from the database. Quote from the docs:

    ignored_columns=(columns)

    Sets the columns names the model should ignore. Ignored columns won't have attribute accessors defined, and won't be referenced in SQL queries.

    Just add the following to your model:

    class MyModel < ApplicationRecord
      self.ignored_columns = %w(hash)
    end