是否有可能有一个活动记录 has_many 关联,但我有一个特定的条件。
class Team < AR
has_many :matches, query: 'team1 == ID or team2 == ID'
end
class Match < AR
attr_accessible :team1, :team2
end
是否有可能有一个活动记录 has_many 关联,但我有一个特定的条件。
class Team < AR
has_many :matches, query: 'team1 == ID or team2 == ID'
end
class Match < AR
attr_accessible :team1, :team2
end
这是一个潜在的解决方案:
class Team < AR
def matches
Match.where("team1 = ? or team2 = ?", id, id) # or: { team1: id, team2: id }
end
end
你可以使用finder_sql
,但它会在 Rails 4 中被弃用,我不确定是否有新的方法可以做到这一点:
class Team < AR
has_many :matches, finder_sql: proc { "SELECT * FROM matches WHERE (matches.team1 = #{id} or matches.team2 = #{id})" }
end
另一种解决方案:
class Team < AR
has_many :matches_as_team1, class_name: "Match", foreign_key: "team1"
has_many :matches_as_team2, class_name: "Match", foreign_key: "team2"
def matches
matches_as_team1 | matches_as_team2
end
end
在此解决方案中, 的结果Team#matches
是一个数组,而不是 a Relation
,因此您将无法执行类似team.matches.limit(10)
.
我希望您的关联保持正常,并稍后在 where 条件下应用查询。
class Team < AR
has_many :matches
scope :team_details, lambda {|id1,id2| matches.where("team1 = ? OR team2 = ?",id1,id2)}
end
团队(团队的对象)
然后打电话
team.team_details(id1,id2)