Sobes.tech
Middle

What is ActiveRecord Relation?

sobes.tech AI

Answer from AI

ActiveRecord Relation is a lazily loaded object representing a set of records from a database. It stores query conditions (WHERE, ORDER BY, LIMIT, etc.) but does not execute the query until data access is required.

Main properties:

  • Lazy loading: The database query is executed only when necessary (e.g., when iterating over the collection or calling the .to_a method).
  • Method chaining: Methods can be called sequentially to add conditions to the query (e.g., User.where(active: true).order(:created_at)).
  • Mutability: The Relation can be modified by adding or removing conditions before executing the query.
  • Array-like interface: Relation behaves like an array, supporting many array methods.

Example:

# Creating a Relation without executing the query
users = User.where(status: 'active')

# Adding another condition, query still not executed
active_admins = users.where(role: 'admin')

# Query executes on the first iteration over the collection
active_admins.each do |user|
  puts user.name
end

Advantages of using Relation:

  • Efficiency: Database queries are executed only when needed, improving performance.
  • Readability: Method chaining makes queries clearer.
  • Flexibility: Conditions can be modified before execution.

Although similar to arrays, Relation has some differences:

  • Does not cache data: Each time data is accessed, Relation may execute the query again (unless .to_a is used).
  • Does not support all Array methods: Some specific array methods may be absent.