toArray / to_a
rel.to_arel.toArray()Problem
Section titled “Problem”Convert a relation to a plain array for further processing or output.
Example: I’ve built my query and now want the results as an array for JSON serialization.
Description
Section titled “Description”This operator materializes a relation into a plain array of tuples/objects. This is typically the final step in a query chain when you need to work with the results as regular data.
Requirements
Section titled “Requirements”None. Works on any relation.
Examples
Section titled “Examples”suppliers .restrict(city: "Paris") .project([:sid, :name]) .to_a
=> [{:sid=>"S2", :name=>"Jones"}]suppliers .restrict({ city: "Paris" }) .project(['sid', 'name']) .toArray()
// => [{ sid: "S2", name: "Jones" }]For JSON serialization
Section titled “For JSON serialization”require 'json'
data = suppliers .project([:name, :city]) .to_a
JSON.generate(data)# => '[{"name":"Smith","city":"London"},{"name":"Jones","city":"Paris"}]'const data = suppliers .project(['name', 'city']) .toArray()
JSON.stringify(data)// => '[{"name":"Smith","city":"London"},{"name":"Jones","city":"Paris"}]'