I'm having an issue performing a query for only objects that are active. I do not have an active column in the database, instead, on a model Game, I have the following method:
def complete?
self.winner ? true : false
end
That way if a Game has a Winner, #complete?
will return true. I want to query for all Games that would return false for this method, is there a way to do this with ActiveRecord? Right now in my controller I'm simply calling @games = Game.all
, and then in my partial rendering games like:
<% unless game.complete? %>
yada yada
<% end %>
This seems kind of hacky, and would require me to write a different partial if I want to display "completed" games. Anyway, I was wondering if there is a way in the controller to only assign objects that would return true/false from a model method?
What about a fast and easy class method?
class Game < ActiveRecord::Base
def self.completed_games
games = []
Game.all.each { |game| games << game if game.complete? }
return games
end
end
Then call Game.completed_games
. You can make one for incomplete games too. You can make that method one line too, but I broke it up so you can see exactly what's going on.
Since winner
is a property of Game
, why not query on that? You just need this:
completed = Game.where('winner is not null')
incomplete = Game.where('winner is null')
You could also make them scopes if you so desired:
class Game < ActiveRecord::Base
scope :finished, where('winner is not null')
scope :unfinished, where('winner is null')
#...
end
and then you could add further filtering or ordering before anything comes out of the database.
Let the database do the work, they're good at searching and slinging data around. Any time you're pulling an entire table out of the database for client-side processing you should think again as you're almost certainly making a mistake.
you can do like this
Game.all.select{ |game| game.complete? }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With