Ruby on rails 有多个,属于多个外键
我试图通过一种“有很多,属于”的关系将比赛归于一家俱乐部。然而,在比赛中,我需要将俱乐部设置为主队或客队。为了解决这个问题,我使用了两个外键Ruby on rails 有多个,属于多个外键,ruby-on-rails,foreign-keys,has-many,belongs-to,Ruby On Rails,Foreign Keys,Has Many,Belongs To,我试图通过一种“有很多,属于”的关系将比赛归于一家俱乐部。然而,在比赛中,我需要将俱乐部设置为主队或客队。为了解决这个问题,我使用了两个外键 class Club < ActiveRecord::Base has_many :matches end class Match < ActiveRecord::Base belongs_to :home_team, class_name: 'Club', foreign_key: 'home_team_id' belongs_
class Club < ActiveRecord::Base
has_many :matches
end
class Match < ActiveRecord::Base
belongs_to :home_team, class_name: 'Club', foreign_key: 'home_team_id'
belongs_to :away_team, class_name: 'Club', foreign_key: 'away_team_id'
end
如何更改关系以便执行此操作?您可以定义外键
class Club < ActiveRecord::Base
has_many :home_matches, class_name: 'Match', foreign_key: 'home_team_id'
has_many :away_matches, class_name: 'Match', foreign_key: 'away_team_id'
end
然后你就可以进行@club.matches
class Club < ActiveRecord::Base
has_many :club_matches
has_many :matches, through: :club_matches
end
class ClubMatch < ActiveRecord::Base
belongs_to :club
belongs_to :match
#will have an attribute on it to determine if home or away team
end
class Match < ActiveRecord::Base
has_many :club_matches
has_many :clubs, through: :club_matches
end
这只是我最初的想法,有人可能会想出更好的解决办法
假设您可以在没有关联的情况下执行查询,这对您来说可能更好,重构更少。比如说
class WhateverController < ApplicationController
def matches
@club = Club.find(params[:club_id)
@matches = Match.where("home_team_id = :club_id OR away_team_id = :club_id", {club_id: @club.id}).order(:date)
end
class WhateverController
我的答案就是给你的
至于你的代码,这里是我的修改
class Club < ActiveRecord::Base
has_many :matches, ->(club) { unscope(where: :club_id).where("home_team_id = ? OR away_team_id = ?", club.id, club.id) }, class_name: 'Match'
end
class Match < ActiveRecord::Base
belongs_to :home_team, class_name: 'Club', foreign_key: 'home_team_id'
belongs_to :away_team, class_name: 'Club', foreign_key: 'away_team_id'
end
class Club(俱乐部){unscope(where::club_id)。where(“主队_id=?或客队_id=?”,club.id,club.id)},班级名称:'Match'
结束
类匹配
有什么问题吗?我认为你的查询是对的。考虑到这个解决方案后,关联似乎没有必要!谢谢!不用担心,有时候你看不到树木的真实情况。写了一半就有很多问题,然后认为你可以在一个忽略关联的查询中完成。我有这个问题我也有
用户
和消息。from\u id
和消息。to\u id
。我正在尝试有很多消息,->(u){其中“from\u id=?或to\u id=?”,u.id,u.id},外键:nil
没有成功。unscope做什么?第一个类名似乎没有必要。哇,这很有效有很多:消息,->(u){unscope(where::user_id)。其中“from_id=?或to_id=?”,u.id,u.id}
产生u.messages消息加载(15.6ms)从“messages”中选择“messages”。*其中(从\u id=1或到\u id=1)
class Club < ActiveRecord::Base
has_many :matches, ->(club) { unscope(where: :club_id).where("home_team_id = ? OR away_team_id = ?", club.id, club.id) }, class_name: 'Match'
end
class Match < ActiveRecord::Base
belongs_to :home_team, class_name: 'Club', foreign_key: 'home_team_id'
belongs_to :away_team, class_name: 'Club', foreign_key: 'away_team_id'
end