Reputation: 204
I have been searching online but I had no luck to get the best way to do this.
I have a controller, in that controller I execute a sql query to retrieve all requests from a user
@solicitudes = Solicitud.where("user_id = ?",@current_user.id)
And I want to know how to transfer each data row on the main object to the proper object with all requests with the same status. I have tried:
@solicitudes.each do |solicitud|
if solicitud.estado == 1
@solicitudes_pendientes << solicitud
else
if solicitud.estado == 2
@solicitudes_aprobadas << solicitud
else
if solicitud.estado == 3
@solicitudes_rechazadas << solicitud
end
end
end
end
But clearly is not working.
At the moment I am using 3 sql queries to retrieve all requests into their corresponding objects but that takes 3 x time + 2 extra transactions:
@solicitudes_pendientes = Solicitud.where("estado = 1 and user_id = ?",@current_aplicante.id)
@solicitudes_aprobadas = Solicitud.where("estado = 2 and user_id = ?",@current_aplicante.id)
@solicitudes_rechazadas = Solicitud.where("estado = 3 and user_id = ?",@current_aplicante.id)
Waiting for any useful advise. Thank you.
Upvotes: 0
Views: 36
Reputation: 29124
You can use Enumerable#group_by
@solicitudes = Solicitud.where(:user_id => @current_user.id).entries.group_by(&:estado)
which will give you a Hash of the form
{
1 => [#<Solicitud estado: 1>, #<Solicitud estado: 1>],
2 => [#<Solicitud estado: 2>, #<Solicitud estado: 2>, ..],
3 => ..,
..
}
You can access them like
@solicitudes_pendientes = @solicitudes[1]
Upvotes: 1