我正在尝试将标签搜索作为 Texticle 搜索的一部分。由于 texticle 不会从同一模型中搜索多个表,因此我最终创建了一个名为 PostSearch 的新模型,遵循 Texticle 关于 System-Wide Searching 的建议
class PostSearch < ActiveRecord::Base
# We want to reference various models
belongs_to :searchable, :polymorphic => true
# Wish we could eliminate n + 1 query problems,
# but we can't include polymorphic models when
# using scopes to search in Rails 3
# default_scope :include => :searchable
# Search.new('query') to search for 'query'
# across searchable models
def self.new(query)
debugger
query = query.to_s
return [] if query.empty?
self.search(query).map!(&:searchable)
#self.search(query) <-- this works, not sure why I shouldn't use it.
end
# Search records are never modified
def readonly?; true; end
# Our view doesn't have primary keys, so we need
# to be explicit about how to tell different search
# results apart; without this, we can't use :include
# to avoid n + 1 query problems
def hash
id.hash
end
def eql?(result)
id == result.id
end
end
在我的 Postgres DB 中,我创建了一个这样的视图:
CREATE VIEW post_searches AS
SELECT posts.id, posts.name, string_agg(tags.name, ', ') AS tags
FROM posts
LEFT JOIN taggings ON taggings.taggable_id = posts.id
LEFT JOIN tags ON taggings.tag_id = tags.id
GROUP BY posts.id;
这使我可以得到这样的帖子:
SELECT * FROM post_searches
id | name | tags
1 Intro introduction, funny, nice
所以看起来一切都应该没问题。不幸的是,调用 PostSearch.new("funny") 返回 [nil] (NOT [])。翻阅 Texticle 源代码,好像 PostSearch.new 中的这一行
self.search(query).map!(&:searchable)
使用某种 searchable_columns 方法映射字段,它是否正确?结果为零。
另一方面,除非我将其从文本类型转换为 varchar 类型,否则不会在 texticle SQL 查询中搜索标签字段。
所以,总而言之:为什么找到对象时它会被映射到 nil ?
和
为什么 texticle 会忽略我的标签字段,除非它是 varchar?