我正在使用带有 pg_search gem 的 postgres 全文搜索。搜索本身运行良好,但我需要进一步过滤结果,以下是详细信息:
class Notebook < ActiveRecord::Base
has_many :invites
def self.text_search(query)
if query.present?
search(query)
else
scoped
end
end
笔记本 Controller :
def index
if params[:query].present?
@notebooks = Notebook.text_search(params[:query]).includes(:invites).where("invites.email = :email OR notebooks.access = :access OR notebooks.access = :caccess OR notebooks.user_id = :uid", email: current_user.email, access: "open", caccess: "closed", uid: current_user.id)
else
@notebooks = Notebook.includes(:invites).where("invites.email = :email OR notebooks.access = :access OR notebooks.access = :caccess OR notebooks.user_id = :uid", email: current_user.email, access: "open", caccess: "closed", uid: current_user.id)
end
我收到的错误是“缺少表‘邀请’的 FROM 子句条目”。我尝试过很多不同的东西,包括:
- 将“包含”替换为“加入”
- 将'includes(:invites) 替换为 joins('LEFT JOIN "invites"ON "invites"."email"= "email"')
- 更改 .text_search 和 .includes 调用的顺序。
- 在 Controller 、模型、作用域和 text_search 函数定义中添加包含调用。
我不断收到同样的错误,当使用 SQL 的连接调用时,它不会按邀请电子邮件进行过滤,而是显示每个搜索结果的多个重复项。
我只想删除 include(:invites) 因为 text_search 本身工作得很好。但我真的需要包括这个条件。
如有任何帮助,我们将不胜感激。也许我只是把我的 SQL 调用弄错了,但我也想了解为什么 .includes(:invites) 可以在没有 pg text_search 的情况下工作,但不能使用它。
编辑 #1 - 更具体的问题
我认为这里有 2 个略有不同的问题。第一个似乎是结合 pg_search gem 和 'includes(:invites)' 调用的一些问题。第二个问题是我可以使用什么等效的 SQL 语句来避免调用“includes(:invites)”。我认为它应该是某种 LEFT JOIN,但我认为我做的不正确。在我的数据库中,一个笔记本有很多邀请,并且邀请有一个属性“电子邮件”。我需要带有与 current_user 的电子邮件相同的电子邮件的邀请的笔记本。
如果能帮助解决其中任何一个问题,那就太好了。
最佳答案
这是向我展示问题解决方案的链接: https://github.com/Casecommons/pg_search/issues/109
这是我的具体代码:
class Notebook < ActiveRecord::Base
has_many :invites
include PgSearch
pg_search_scope :search, against: [:title],
using: {tsearch: {dictionary: "english"}},
associated_against: {user: :name, notes:[:title, :content]}
scope :with_invites_and_access, lambda{ |c_user_email|
joins('LEFT OUTER JOIN invites ON invites.notebook_id = notebooks.id').where('invites.email = ? OR notebooks.access = ? OR notebooks.access = ?', c_user_email, 'open', 'closed')
}
def self.text_search(query)
if query.present?
search(query).with_invites_and_access(current_user_email)
else
scoped
end
end
end
关键是连接语句。加入(:邀请)不起作用,包括(:邀请)不起作用。需要完整的 SQL 语句:
joins('LEFT OUTER JOIN invites ON invites.notebook_id = notebooks.id')
关于sql - 使用 pg_search 的 Postgres 全文搜索 - 包括(:child_model) breaks the SQL with 'missing FROM-clause entry for table ' child_model',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19339417/