Fajarmf
Fajarmf

Reputation: 2273

rails active record has_many custom query

is it possible to have an active record has_many associations, but i have a specific condition.

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

class Match < AR
  attr_accessible :team1, :team2
end

Upvotes: 2

Views: 11406

Answers (3)

DRobinson
DRobinson

Reputation: 4471

Here's a potential solution:

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

Upvotes: 6

Micha&#235;l Witrant
Micha&#235;l Witrant

Reputation: 7714

You can use finder_sql but it will be deprecated in Rails 4 and I'm not sure if there's a new way to do this:

class Team < AR
  has_many :matches, finder_sql: proc { "SELECT * FROM matches WHERE (matches.team1 = #{id} or matches.team2 = #{id})" }
end

Another solution:

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

In this solution, the result of Team#matches is an array, not a Relation, so you won't be able to do things like team.matches.limit(10).

Upvotes: 3

AnkitG
AnkitG

Reputation: 6568

I would prefer keeping your association as normal and apply query later on with where condition.

class Team < AR
  has_many :matches

  scope :team_details, lambda {|id1,id2| matches.where("team1 = ? OR team2 = ?",id1,id2)} 
end

team (object of Team)

Then call

team.team_details(id1,id2)

Upvotes: 1

Related Questions