Algolia Search tagging based on Rails associations,如何在关联为created/destroyed时更新标签?
Algolia Search tagging based on Rails associations, how to update tags when association is created/destroyed?
我有一个简单的 algolia 设置,其中包含几个模型,每个模型都有一些属性,例如:
class User < ActiveRecord::Base
include AlgoliaSearch
algoliasearch do
attributes :id, :name
add_attribute :_tags
end
def _tags
users = []
self.connections.each do |connection|
users.push('user_' + connection.user_id.to_s)
end
users
end
end
上面的设置很容易让我限制每个用户的搜索结果,这样用户只能看到他们有权查看的记录,如果他们在 Rails 应用程序中 associated/related .
但是,当创建或销毁 Connection
模型时,User
模型并不知道,从而对搜索结果产生负面影响。
如何向 Connection
模型添加 ActiveRecord 回调并相应地更新记录上的 _tags
键,以便更新 _tags
以包含或排除(基于创建或销毁)?
tldr:Algolia 的记录中的 _tags
的值 ['user_1', 'user_2']
由 Rails 中的关联确定。 Algolia 中的记录与 user_2
之间的关联已从 Rails 中的数据库中删除,如何从 Algolia 中记录的标签数组中删除 user_2
?
GitHub 上有一个关于此的 pending issue:检测底层关联的变化。
同时,您可以在 Connection
对象的 after_save 回调中强制索引 User
对象:
class User
algoliasearch do
# [...]
end
end
class Connection
after_save :reindex_user
belongs_to :user
private
def reindex_user
self.user.reindex!
end
end
我有一个简单的 algolia 设置,其中包含几个模型,每个模型都有一些属性,例如:
class User < ActiveRecord::Base
include AlgoliaSearch
algoliasearch do
attributes :id, :name
add_attribute :_tags
end
def _tags
users = []
self.connections.each do |connection|
users.push('user_' + connection.user_id.to_s)
end
users
end
end
上面的设置很容易让我限制每个用户的搜索结果,这样用户只能看到他们有权查看的记录,如果他们在 Rails 应用程序中 associated/related .
但是,当创建或销毁 Connection
模型时,User
模型并不知道,从而对搜索结果产生负面影响。
如何向 Connection
模型添加 ActiveRecord 回调并相应地更新记录上的 _tags
键,以便更新 _tags
以包含或排除(基于创建或销毁)?
tldr:Algolia 的记录中的 _tags
的值 ['user_1', 'user_2']
由 Rails 中的关联确定。 Algolia 中的记录与 user_2
之间的关联已从 Rails 中的数据库中删除,如何从 Algolia 中记录的标签数组中删除 user_2
?
GitHub 上有一个关于此的 pending issue:检测底层关联的变化。
同时,您可以在 Connection
对象的 after_save 回调中强制索引 User
对象:
class User
algoliasearch do
# [...]
end
end
class Connection
after_save :reindex_user
belongs_to :user
private
def reindex_user
self.user.reindex!
end
end