Reputation: 1336
I execute a query using find_by_sql
and one of the attributes I return is the count(*)
. But I want to just extract the count for a different variable and delete it from the models returned. Here's an example of the query:
Model.find_by_sql("select prop1, sum(prop2), count(*) OVER() AS full_count from table
group by prop1
limit 3")
I get an array of Model
with the attributes (Model.attributes
) like this:
[{prop1: "A", prop:3, full_count: 20}, {prop1: "B", prop:4, full_count: 20}, {prop1: "C", prop:6, full_count: 20}]
And that's what gets rendered to the front end.
But basically I'm going to store the full_count
attribute in one variable and I want to delete it from the objects in the array. So I'd want the results to be:
[{prop1: "A", prop:3}, {prop1: "B", prop:4}, {prop1: "C", prop:6}]
I tried doing this:
query_result.each do |obj|
obj.attributes.delete('full_count')
end
But that didn't work.
Any help would be greatly appreciated! I tried searching but did not find anything that worked.
Upvotes: 2
Views: 75
Reputation: 186
If you are rendering as JSON you could do this
query_result = Model.find_by_sql("select prop1, sum(prop2), count(*) OVER() AS full_count
from table
group by prop1
limit 3")
full_count = query_result.first.full_count
query_result.as_json(except: :full_count)
Upvotes: 1
Reputation: 1407
Try the below:
query_result = Model.find_by_sql("select prop1, sum(prop2), count(*) OVER() AS full_count from table
group by prop1
limit 3")
result = query_result.map do |obj|
obj.attributes.slice('prop1', 'prop')
end
Upvotes: 0