views:

22

answers:

1

How can I write the code below so that it passes the user.id. Given what I have, it throws Class id not found error. (User has many fights. And Fight belongs to user. User can either be a challenger in the fight, or a challengee in the other.)

has_many :fight_wins, :class_name => 'Fight', :foreign_key => 'challenger_id or challengee_id', 
  :conditions => ["(challenger_id = ? and challenger_won = ?) or (challengee_id = ? and challenger_won = ?)", self.id, true, self.id, false]
A: 

You can use the finder_sql option for complex has_many conditions:

has_many :fight_wins, :class_name => 'Fight', :finder_sql =>
      '#{sanitize_sql_array(
          "SELECT f.* 
           FROM   fights AS f 
           WHERE  (f.challenger_id = ? AND f.challenger_won = ?) OR 
                  (f.challengee_id = ? AND f.challenger_won = ?)
          ", id, true, id, false)}'
KandadaBoggu
when i run this, it's saying id not defined local variable or method
keruilin
updated the answer try again.
KandadaBoggu