Sunspot Solr:将来自同一 has_many 关联的多个属性匹配在一起?
Sunspot Solr: Match multiple attributes together from a same has_many association?
假设我们有两个用户,
用户 A,有:
- 'Ruby' 的技能和 '5'experience_years 的技能
- 'HTML' 的技能和“7”experience_years 的技能
用户 B,有:
- '2''Ruby' 和 experience_years 的技能
- 'HTML' 的技能和 '5'experience_years 的技能
我只想匹配用户A,即有5年Ruby经验的用户
下面的控制器和模型代码匹配用户 A 和 B,因为 skill
和 experience_years
是单独评估的,两个用户都有 'Ruby' 和 '5',只是没有在一起。
如何编写控制器(或模型)部分以仅匹配用户 A?
型号
class User < ApplicationRecord
has_many :user_skills
searchable do
text :skill do
user_skills.map { |r| r.skill.name }
end
text :experience_years do
user_skills.pluck(:experience_years)
end
end
end
class UserSkill < ApplicationRecord
belongs_to :user
belongs_to :skill
end
class Skill < ApplicationRecord
end
控制器
class UsersController < ApplicationController
def index
sunspot = User.search do
fulltext 'Ruby' do
fields(:skill)
end
fulltext '31' do
fields(:experienceYears)
end
end
@users = sunspot.results
end
end
解决方案是使用动态整数。
模型(在可搜索块内):
# skill + experienceYears composite field:
dynamic_integer :skill_composite do
if skills
skills.inject({}) do |hash, e|
hash.merge(e.skill.skill_code => e.experience_years)
end
end
end
控制器:
with(skill_code).equal_to experience_years
注意使用skill_code
而不是name
,这是因为字符串中的空格等特殊字符会引起麻烦。在这种情况下,skill_code
是 name 的一种参数化值。
假设我们有两个用户,
用户 A,有:
- 'Ruby' 的技能和 '5'experience_years 的技能
- 'HTML' 的技能和“7”experience_years 的技能
用户 B,有:
- '2''Ruby' 和 experience_years 的技能
- 'HTML' 的技能和 '5'experience_years 的技能
我只想匹配用户A,即有5年Ruby经验的用户
下面的控制器和模型代码匹配用户 A 和 B,因为 skill
和 experience_years
是单独评估的,两个用户都有 'Ruby' 和 '5',只是没有在一起。
如何编写控制器(或模型)部分以仅匹配用户 A?
型号
class User < ApplicationRecord
has_many :user_skills
searchable do
text :skill do
user_skills.map { |r| r.skill.name }
end
text :experience_years do
user_skills.pluck(:experience_years)
end
end
end
class UserSkill < ApplicationRecord
belongs_to :user
belongs_to :skill
end
class Skill < ApplicationRecord
end
控制器
class UsersController < ApplicationController
def index
sunspot = User.search do
fulltext 'Ruby' do
fields(:skill)
end
fulltext '31' do
fields(:experienceYears)
end
end
@users = sunspot.results
end
end
解决方案是使用动态整数。
模型(在可搜索块内):
# skill + experienceYears composite field:
dynamic_integer :skill_composite do
if skills
skills.inject({}) do |hash, e|
hash.merge(e.skill.skill_code => e.experience_years)
end
end
end
控制器:
with(skill_code).equal_to experience_years
注意使用skill_code
而不是name
,这是因为字符串中的空格等特殊字符会引起麻烦。在这种情况下,skill_code
是 name 的一种参数化值。