2

我有以下模型关联,我想使用这些关联来搜索玩家

class Player < ActiveRecord::Base
 belongs_to :user
 has_many :abilities
 has_many :sports, :through => :abilities
 ...
end

class User < ActiveRecord::Base
  has_one :player
...
end

class Ability < ActiveRecord::Base
  belongs_to :player
  belongs_to :sport
  has_one :level
  ...
end

class Sport < ActiveRecord::Base
  has_and_belongs_to_many :category_sports 

  has_many :abilities
  has_many :players, :through => :abilities
  ...
end

class CategorySport < ActiveRecord::Base
 has_and_belongs_to_many :sports 
end

我有一个表格,用户可以填写两个输入:城市运动

城市字段在用户模型中为 ( @user.city),运动字段可以在 CategorySport 中为 ( @category_sport.name) 或在运动模型中为 ( @sport.name)。

现在我有以下在Player模型中执行搜索:

def search
  self.find(:all,:include => 'user',:conditions => ['users.city LIKE ?', "%#{city}%"])
end

我想知道如何在此查询中添加连接模型(能力)和相关(运动、类别运动),以便也按运动查找。因此,不仅可以查找用户城市,还可以查找运动。

4

1 回答 1

1

试试这个:

def search
  self.includes(:user, :abilities => {:sport => :category_sports}).
    where(['users.city LIKE ? OR category_sports.name=? OR sports.name=?', 
      "%#{city}%", sport, sport])
end
于 2012-07-11T18:18:45.593 回答