【问题标题】:How can I write this query efficiently in Ruby on Rails?如何在 Ruby on Rails 中高效地编写此查询?
【发布时间】:2010-11-20 08:51:03
【问题描述】:

我有三个表:Accounts、Investments 和 Games。投资具有 account_id、game_id、一些统计计数器,并在 Account 第一次参与游戏时创建。

我想提供最新游戏的 JSON 列表以及用户对该游戏的投资,如下所示:

[{id: 666, name: "Foobar", ..., investment: {tokens: 58, credits: 42, ...}},...]

如果他们还没有参与游戏,我仍然想包含一个具有默认值的投资对象,所以我在我的游戏模型中覆盖了serializable_hash 函数:

# game.rb
has_many :investments
def serializable_hash(options=nil)
  options ||= {}
  i = investments.find_or_initialize_by_account_id options[:uid]
  {:id => id, ..., :investment => i.serializable_hash}
end

但是,当我运行 Game.find(list_of_ids).to_json(:uid => current_user.id) 之类的东西时,Rails 会针对每个游戏的 Investments 表进行单独的查询。我试过Game.includes(:investments).find(list_of_ids).to_json(:uid => current_user.id),但它不仅会为所有用户加载投资,它还会为每个游戏单独查询以查找或初始化投资对象。

简而言之,给定一个游戏 ID 列表和一个帐户 ID,加载一个查询中存在的相关投资对象并初始化其余对象的干净方法是什么?

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-3


    【解决方案1】:

    您想一次性将 id 列表提供给服务器。我为此使用IN 运算符:

    Game.includes(:investments).where("games.id IN (?)", list_of_ids)
    

    【讨论】:

    • 运行与我上面相同的查询,Game.includes(:investments).find(list_of_ids)
    • @Violet 在这种情况下,必须是 includes 调用将它们分开。
    猜你喜欢
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多