Rails 7.1 allows resetting singular associations

In Rails, to reset associations and clear the cache for a specific association, we can use the reset method. This method reloads the association and clears any cached data related to it.

class Client < ApplicationRecord
  has_many :invoices
  has_one :project
end

class Invoice < ApplicationRecord
  belongs :client
end

class Project < ApplicationRecord
  belongs :client
end
client = Client.first

client.invoices 

# => returns the array of invoices. e.g: 3 invoices
# Let's delete one invoice

client.invoices.first.destroy

# Let's check client invoices

client.invoices

# => it's still 3 invoices (Due to caching)
# Let's reset associations and clear the cache

client.invoices.reset

# => queries the database again and this time it will show 2 invoices.

Before

If we observe the above example, we reset associations and cleared the cache on has_many associations. But for singular associations, we can not reset and clear the cache.

client.project

# => returns the project.
# Let's delete the project

client.project.destroy

# Let's check the client project

client.project

# => It still shows the single project (Due to caching)
# Let's reset associations and clear the cache

client.project.reset

# => NoMethodError (`method_missing': undefined method reset`)

Before Rails 7.1, to reset the associations and clear the cache, we can use the reload association method.

client.project

# => returns the project.
# Let's delete the project

client.project.destroy

# Let's check the client project

client.project

# => It still shows the single project (Due to caching)
# Let's reset associations and clear the cache

client.reload_project

# => queries the database again and this time it will show no project.

But there is no reset method on singular associations.

After

Rails 7.1 allows resetting singular associations.

has_one and belongs_to associations now define a reset_association method on the owner model (where association is the name of the association).

This method unloads the cached associate record, if any, and causes the next access to query it from the database.

client.project

# => returns the project.
# Let's delete the project

client.project.destroy

# Let's check the client project

client.project

# => it's still shows the single project (Due to caching)
# Let's reset associations and clear the cache

client.reset_project

# => queries the database again and this time it will show no project.

With this refined approach, we can easily reset singular associations and handle association caching.

Need help on your Ruby on Rails or React project?

Join Our Newsletter