Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query with a model method?

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?

like image 536
Kombo Avatar asked Jan 23 '12 19:01

Kombo


3 Answers

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.

like image 107
MrDanA Avatar answered Nov 14 '22 06:11

MrDanA


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.

like image 7
mu is too short Avatar answered Nov 14 '22 05:11

mu is too short


you can do like this

    Game.all.select{ |game| game.complete? }
like image 4
AhmedShawky Avatar answered Nov 14 '22 07:11

AhmedShawky