我正在使用带有 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 子句条目。我尝试了很多不同的东西,包括:
  • 用 'joins' 替换 'includes'
  • 将 'includes(:invites) 替换为 joins('LEFT JOIN "invites"ON "invites"."email"= "email"')
  • 更改 .text_search 和 .includes 调用的顺序。
  • 在 Controller 、模型、范围和 text_search 函数定义中添加包含调用。

  • 我不断收到同样的错误,当使用 SQL 的 joins 调用时,它不会通过邀请电子邮件进行过滤,并显示每个搜索结果的多次重复。

    我只想删除 include(:invites) 因为 text_search 本身工作得很好。但我真的需要包括这个条件。

    任何帮助将不胜感激。也许我只是把我的 SQL 调用弄错了,但我也想了解为什么 .includes(:invites) 在没有 pg text_search 的情况下工作但不能使用它。

    编辑 #1 - 更具体的问题

    我认为这里有两个略有不同的问题。第一个似乎是结合 pg_search gem 和 'includes(:invites)' 调用的一些问题。第二个问题是我可以使用的等效 SQL 语句是什么,以避免进行 'includes(:invites)' 调用。我认为它应该是某种LEFT JOIN,但我认为我做得不对。在我的数据库中,一个 Notebook has_many 邀请,并且邀请有一个属性“电子邮件”。我需要带有邀请的笔记本,其电子邮件与 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
    

    关键是 joins 语句。 joins(:invites) 不起作用,includes(:invites) 不起作用。需要完整的 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/

    10-12 19:48