Rub*_*tic 5 ruby-on-rails ruby-on-rails-3 sunspot-rails sunspot-solr
如何在SunSpot Solr中正确搜索多个模型?
档案模型
has_one :match
searchable do
string :country
string :state
string :city
end
Run Code Online (Sandbox Code Playgroud)
匹配模型
belongs_to :profile
searchable do
string :looking_for_education
integer :age_from
integer :age_to
end
Run Code Online (Sandbox Code Playgroud)
ProfilesController#指数
def index
@search = Sunspot.search Profile, Match do
with(:country, params[:country])
with(:state, params[:state])
with(:looking_for_education, params[:looking_for_education]) <= from the 2nd model
end
@profiles = @search.results
end
Run Code Online (Sandbox Code Playgroud)
这失败了:
Using a with statement like
with(:age).between(params[:age_from]..params[:age_to])
undefined method `gsub' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)
删除
with(:age).between(params [:age_from] .. params [:age_to])行然后尝试
然后它试图加载
view app/views/educators/educator.html.haml
Run Code Online (Sandbox Code Playgroud)
它不存在(我只使用
/app/views/profiles/_profile.html.haml
Run Code Online (Sandbox Code Playgroud)
显示个人资料
什么是使用太阳黑子和solr的红宝石轨道上的优秀开源项目,以更先进的方式来看看?也许我可以在那里找到答案.如果这个问题导致了这个问题,那么这个方向的任何答案也将被接受.
您找到的搜索多个模型的方法是正确的.但是,您的搜索的含义似乎并非您的意图.看起来好像你想说:
给我所有
Profile
的记录与这些country
和state
价值观,以及其Match
记录有该looking_for_education
值
但是,您的搜索说:
给我类型的所有记录
Profile
或Match
具有所有这些country
,state
和looking_for_education
值
由于它们各自的块中既没有Profile
也Match
没有所有这些字段searchable
,因此没有一条记录可以匹配您指定的条件.
如果我对上面的预期行为是正确的,那么您需要在配置文件的searchable
块中包含配置文件的关联匹配信息,如下所示:
class Profile < ActiveRecord::Base
has_one :match
searchable do
string(:country)
string(:state)
string(:city)
string(:looking_for_education) { match.looking_for_education }
integer(:age_from) { match.age_from }
integer(:age_to) { match.age_to }
end
end
Run Code Online (Sandbox Code Playgroud)
在这里,我们告诉Sunspot将配置文件匹配关联的属性编入索引,就好像它们存在于配置文件本身一样.在相应的块中,我们告诉Sunspot如何在索引配置文件时填充这些值.
这将允许您仅使用Profile
模型编写搜索:
def index
@search = Sunspot.search Profile do
with(:country, params[:country])
with(:state, params[:state])
with(:looking_for_education, params[:looking_for_education])
with(:age).between(params[:age_from]..params[:age_to])
end
@profiles = @search.results
end
Run Code Online (Sandbox Code Playgroud)
此搜索将仅返回Profile
记录,同时仍反映每个配置文件的匹配关联的属性,因为我们在对配置文件编制索引时存储它们.
请注意,在索引模型时会增加复杂性.如果Match
记录发生更改,则现在需要重新编制其关联的配置文件以反映这些更改.
归档时间: |
|
查看次数: |
3464 次 |
最近记录: |