Rails 7.1 Raises Error When Generating Model Attributes With Reserved Names.

ActiveRecord migrations are a convenient way to modify our database schema over time.

They allow us to create, modify, and manage database tables and columns, ensuring consistency across environments.

Before

Currently, ActiveRecord::Migration has a weird behaviour where we can generate migrations with reserved keywords like attributes, type etc.

bin/rails generate model Post title:text attributes:jsonb

class CreatePosts < ActiveRecord::Migration[6.0]
  def change
    create_table :posts do |t|
      t.text :title
      t.jsonb :attributes, default: '{}'
      t.timestamps
    end
  end
end

It generates the migration without any issues. But it raises error when we try to use it.

Post.create!(title: "Hello World", attributes: { category: 1 })

=> attributes is defined by Active Record. 
Check to make sure that you don't have an attribute 
or 
method with the same name. (ActiveRecord::DangerousAttributeError)

After

This problem is now fixed in Rails 7.1 with this PR#47752 where ActiveRecord::Migration raises error when generating model attributes with reserved names

Now we can be sure that our migrations does not contain any reserved words and will not fail during migration because of it.

bin/rails generate model Post title:text attributes:jsonb

=> Could not generate field 'attributes', as it is already defined by Active Record.

Need help on your Ruby on Rails or React project?

Join Our Newsletter