【发布时间】:2018-01-26 19:28:05
【问题描述】:
假设我有以下两个模型,分别由以下两个连接模型连接:
class Game
has_many :game_plays
has_many :game_views
end
class Person
has_many :game_plays
has_many :game_views
end
# Games that a Person has played
class GamePlay
belongs_to :game
belongs_to :person
end
# Games that a Person has viewed
class GameView
belongs_to :game
belongs_to :person
end
给定一个特定的GamePlay,我想为相同的Person-Game 组合获得GameView,例如:
game_play = GamePlay.first
game_view = GameView.find_by(game_id: game_play.game_id, person_id: game_play.person_id)
我还需要预先加载该关联。
我很想在GamePlay 和GameView 之间建立一个关联,但到目前为止我没有尝试过任何方法。
尝试 1
class GamePlay
belongs_to :game
belongs_to :person
has_one :game_view, -> (gp) { where(game_id: gp.game_id) }, foreign_key: :person_id, primary_key: :person_id
end
这行得通,但我不能include这个:
GamePlay.includes(:game_view).first
# => ArgumentError: The association scope 'game_view' is instance dependent (the scope block takes an argument). Preloading instance dependent scopes is not supported.
尝试 2
class GamePlay
belongs_to :game
belongs_to :person
def game_view
GameView.find_by(game_id: game_id, person_id: person_id)
end
end
这显然有效,但我不能包含它,因为它没有被定义为关联。
有什么想法吗?谢谢!
Rails 5.0.0
postgres 9.6.2
【问题讨论】:
标签: ruby-on-rails postgresql activerecord