gpt4 book ai didi

ruby-on-rails - 如何在 Rails 5 中模拟 `OR` 关联的 `has_many` 条件?

转载 作者:行者123 更新时间:2023-12-03 20:32:39 25 4
gpt4 key购买 nike

我要模拟OR has_many 的条件关联所以我不会丢失事件记录关联。我知道这可以使用 scope 来实现或实例方法,但在这种情况下,我将失去关联。

class Game < ActiveRecord::Base
belongs_to :home_team, :class_name => "Team"
belongs_to :away_team, :class_name => "Team"
has_many :sponsors
end
class Sponsor < ActiveReord::Base
belongs_to :game
end
class Team < ActiveRecord::Base
has_many :away_games, :class_name => "Game", :foreign_key => "away_team_id"
has_many :home_games, :class_name => "Game", :foreign_key => "home_team_id"

# what I want here like:
# has_many :games, :foreign_key => [:home_team_id, :away_team_id]
# so I could achieve without losing association helper:
# has_many :sponsors through: :games
end

最佳答案

你可以这样做:

这里会先删除原来的作用域:team_id并使用 away_team_idhome_team_id反而。

has_many :games, ->(team){ unscope(where: :team_id)
.where('away_team_id = :team_id OR home_team_id = :team_id', team_id: team.id) }

has_many :sponsors, through: :games

关于ruby-on-rails - 如何在 Rails 5 中模拟 `OR` 关联的 `has_many` 条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42817331/

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