簡體   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