使用模型方法查询? [英] Query with a model method?

查看:42
本文介绍了使用模型方法查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在仅对活动对象执行查询时遇到问题.我在数据库中没有活动列,而是在模型游戏中,我有以下方法:

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

这样,如果游戏有获胜者,#complete? 将返回 true.我想查询所有会为此方法返回 false 的游戏,有没有办法用 ActiveRecord 做到这一点?现在在我的控制器中,我只是调用 @games = Game.all,然后在我的部分渲染游戏中,例如:

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

然后调用Game.completed_games.你也可以为不完整的游戏制作一个.你也可以把这个方法写成一行,但我把它分开了,这样你就可以清楚地看到发生了什么.

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.

这篇关于使用模型方法查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆