Sim*_*mon 7 ruby-on-rails sunspot sunspot-rails sunspot-solr
我正在使用Sunspot来索引和搜索Rails项目中的几个模型,我需要根据模型与模型的HABTM关联来限制结果Department.这是因为用户可能没有权限查看所有部门的记录,因此不应返回这些部门的结果.
以下是两个模型的重要部分:
class Message < ActiveRecord::Base
has_many :comments, dependent: :destroy
has_and_belongs_to_many :departments
searchable do
text :title, :body
text :comments do
comments.map(&:body)
end
date :created_at
integer :department_ids, using: :department_ids, references: Department, multiple: true
end
end
class Document < ActiveRecord::Base
has_and_belongs_to_many :departments
searchable do
text :name
date :created_at
integer :department_ids, using: :department_ids, references: Department, multiple: true
end
end
Run Code Online (Sandbox Code Playgroud)
这是搜索控制器代码:
class SearchController < ApplicationController
def index
# These arrays are created here for the sake of this example
document_permitted_departments = [1, 2, 3]
message_permitted_departments = [3, 4]
search = Sunspot.search Document, Message do
# This obviously doesn't work
with(:department_ids, document_permitted_departments)
with(:department_ids, message_permitted_departments)
fulltext params[:q]
paginate page: params[:page], per_page: SEARCH_RESULTS_PER_PAGE
order_by :created_at, :desc
end
@results = search.results
@number_of_results = search.total
respond_to do |format|
format.js
format.html
end
end
end
Run Code Online (Sandbox Code Playgroud)
问题是用户可能能够读取部门A和部门B中的文档,但他们应该只能看到部门B中的消息.
有没有办法将with范围应用于多模型搜索中的特定模型?还是有其他方法可以解决这个问题吗?
经过更多的谷歌搜索和一些反复试验后,我终于弄明白了.这是我最终得到的代码的大量注释版本:
class SearchController < ApplicationController
before_filter :authenticate_user!
def index
# These arrays are created here for the sake of this example
# Push 0 on to the end because empty arrays break the `with :department_ids` scopes below
document_permitted_departments = [1, 2, 3].push(0)
message_permitted_departments = [3, 4].push(0)
search = Sunspot.search Document, Message do
any_of do # Return anything that matches any of the scopes in this block
all_of do # Return only those results that match these scopes
with :class, Document # This limits scopes in this block to Document results
with :department_ids, document_permitted_departments
end
all_of do # Return only those results that match these scopes
with :class, Message # This limits scopes in this block to Message results
with :department_ids, message_permitted_departments
end
end
fulltext params[:q]
paginate page: params[:page], per_page: SEARCH_RESULTS_PER_PAGE
order_by :created_at, :desc
end
@results = search.results
@number_of_results = search.total
respond_to do |format|
format.js # index.js.erb
format.html # index.html.erb
end
end
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1221 次 |
| 最近记录: |