Active Record如何为范围关系预加载连接

时间:2017-03-11 19:44:37

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

感谢您查看我的问题。我正在使用Rails 5 API并且遇到特定查询的问题。

我的数据库有2个模型 - 玩家和战斗。战斗表有2个对玩家的外键引用为'winner_id'和'loser_id'。我还有一个范围包括名为'with_results'的赢家和输家:

# models/battle.rb
class Battle < ApplicationRecord

  belongs_to: winner,
    class_name: "Player",
    foreign_key: "winner_id"

  belongs_to: loser,
    class_name: "Player",
    foreign_key: "loser_id"

  scope :with_results, -> { includes(:winner, :loser) }

end

所以我想要实现的是在一个查询中获得战斗表,获胜者的Player表和失败者的Player表。

在rails控制台中,我尝试了一些方法:

Battle.first
# => returns just the battle table with the id's of the winner and loser

Battle.with_results.first
# => returns the same as `Battle.first`

Battle.first.winner
# => returns the winner's Player table

Battle.first.loser
# => returns the loser's Player table

Battle.joins(:winner, :loser).first
# => returns the same as `Battle.first`

同样,我想要做的只是在一个查询中获得战斗,胜利者和失败者,所以我可以发送它的JSON。有没有办法用范围预加载赢家和输家,以便我可以在一个查询中拥有它?

感谢您的任何建议!

1 个答案:

答案 0 :(得分:2)

你快到了!只需告诉to_json包含关联。例如:

Battle.with_results.first.to_json(include: [:winner, :loser])