rails active record has_many自定义查询

时间:2012-08-12 06:35:17

标签: ruby-on-rails activerecord has-many

是否可以有一个活动记录has_many关联,但我有一个特定的条件。

class Team < AR
  has_many :matches, query: 'team1 == ID or team2 == ID'
end

class Match < AR
  attr_accessible :team1, :team2
end

3 个答案:

答案 0 :(得分:3)

使用:conditions指定查询/条件。

例如:

class Team < AR
  has_many :matches, :conditions => ['team1 = #{ID} or team2 = #{ID}']
end

编辑:但是,您可能会遇到该示例的外键问题。这是另一种无论如何都能解决的解决方案:

class Team < AR
  def matches
    Match.where("team1 = #{id} or team2 = #{id}")
  end
end

答案 1 :(得分:1)

您可以使用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的结果是数组,而不是Relation,因此您将无法执行team.matches.limit(10)之类的操作。

答案 2 :(得分:0)

我希望保持您的关联正常,稍后在条件适用的地方应用查询。

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)