gpt4 book ai didi

ruby-on-rails - 具有多个外键的 Rails 预加载关联

转载 作者:行者123 更新时间:2023-11-29 12:24:24 33 4
gpt4 key购买 nike

假设我有以下两个模型,分别由以下两个连接模型连接:

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)

我还需要预先加载该关联。


我很想在 GamePlayGameView 之间建立关联,但目前为止我尝试过的都没有效果。

尝试 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

这行得通,但我不能包含这个:

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

最佳答案

怎么样:

class GamePlay < ApplicationRecord
belongs_to :game
belongs_to :person
has_one :game_view, through: :person, source: :game_views
end

irb(main):002:0> GamePlay.includes(:game_view).find(2)
GamePlay Load (0.2ms) SELECT "game_plays".* FROM "game_plays" WHERE "game_plays"."id" = ? LIMIT ? [["id", 2], ["LIMIT", 1]]
Person Load (0.2ms) SELECT "people".* FROM "people" WHERE "people"."id" = 1
GameView Load (0.2ms) SELECT "game_views".* FROM "game_views" WHERE "game_views"."person_id" = 1
=> #<GamePlay id: 2, game_id: 1, person_id: 1>

irb(main):008:0> GamePlay.find(2).game_view
GamePlay Load (0.1ms) SELECT "game_plays".* FROM "game_plays" WHERE "game_plays"."id" = ? LIMIT ? [["id", 2], ["LIMIT", 1]]
GameView Load (0.2ms) SELECT "game_views".* FROM "game_views" INNER JOIN "people" ON "game_views"."person_id" = "people"."id" WHERE "people"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
=> #<GameView id: 2, game_id: 1, person_id: 1>

关于ruby-on-rails - 具有多个外键的 Rails 预加载关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48468254/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com