Sql Rails:使用联接模型查找-如何?
我想使用以下模型关联来搜索玩家:Sql Rails:使用联接模型查找-如何?,sql,ruby-on-rails-3,activerecord,join,Sql,Ruby On Rails 3,Activerecord,Join,我想使用以下模型关联来搜索玩家: 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
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
我想知道我如何在这个查询中添加加入模型(能力)和相关(运动,分类运动)以便按运动查找。因此,不仅可以通过用户城市查找,还可以通过体育查找。尝试以下方法:
def search
self.includes(:user, :abilities => {:sport => :category_sports}).
where(['users.city LIKE ? OR category_sports.name=? OR sports.name=?',
"%#{city}%", sport, sport])
end
它不起作用。如果城市与任何记录都不一样,它不会返回任何信息……你是说只有在
用户中没有匹配项时才会得到错误的结果吗?真奇怪。我可以查看生成的SQL吗?
def search
self.includes(:user, :abilities => {:sport => :category_sports}).
where(['users.city LIKE ? OR category_sports.name=? OR sports.name=?',
"%#{city}%", sport, sport])
end