我想要使用以下模型关联来搜索玩家:
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
)。
现在我有以下内容在播放器模型中执行搜索:
def search
self.find(:all,:include => 'user',:conditions => ['users.city LIKE ?', "%#{city}%"])
end
我想知道如何在此查询中添加连接模型(能力)和相关(sport,categorysport),以便通过运动查找。所以,不仅要找到用户城市,还要找运动。
答案 0 :(得分: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