Or does Rails do something like automatically adding an index or order by id?
Rails 4.
Yes, you need to add an index yourself for created_at
.
You can look in your migration files and you will see that no index on created_at is defined by default.
It is OK without an index if you have only few hundred rows.
Edit:
Lets assume you have a model named Product
, in order to add an index on created_at
just add a new migration
bundle exec rails d migration AddCreatedAtIndexToProducts
and then open your newly created migration and add the index definition:
class AddCreatedAtIndexToProducts < ActiveRecord::Migration[6.0]
def change
add_index :products, :created_at
end
end
Rails handles adding an index on the primary key column.
As of version 4.2, rails has support for foreign key indexes (note a few gotchas)
Other than that, Rails will leave indexing for all other fields entirely up to you. So no, it won't create one on your created_at
field.
Do you need one? Only if you're running in to performance issues (or see that you'll soon be running in to issues). You can handle much more than just a few hundred rows before running into issues.
Once you do feel you need one, then you should use Rails migrations to add it - you shouldn't add it yourself directly on the database.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With