【问题标题】:How can I simulate `OR` conditions for `has_many` association in Rails 5?如何在 Rails 5 中模拟“has_many”关联的“OR”条件?
【发布时间】:2017-03-15 17:59:36
【问题描述】:

我想模拟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

【问题讨论】:

    标签: ruby-on-rails rails-activerecord ruby-on-rails-5


    【解决方案1】:

    你可以这样做:

    这里会先删除原来的作用域: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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多