繁体   English   中英

如何在Rails 5中模拟“ has_many”关联的“ OR”条件?

[英]How can I simulate `OR` conditions for `has_many` association in Rails 5?

我想模拟has_many关联的OR条件,因此我不会丢失活动记录关联。 我知道可以使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM