gpt4 book ai didi

ruby-on-rails - 使用 Sunspot 查询具有不同属性的多个模型

转载 作者:行者123 更新时间:2023-12-04 11:24:53 30 4
gpt4 key购买 nike

我正在使用 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

这是搜索 Controller 代码:
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

问题是用户可能能够阅读部门 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

关于ruby-on-rails - 使用 Sunspot 查询具有不同属性的多个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21811017/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com