如何使用“rich_text”进行搜索? (Trix编辑)

问题描述 投票:0回答:1

我在我的博客中使用简单的搜索:

post.rb

has_rich_text :content

  def self.search(search)
    where('title ILIKE ? OR content ILIKE ?', "%#{search}%", "%#{search}%")
  end

post_controller.rb

@posts = if params[:search]
  Post.search(params[:search]).order('created_at DESC')
  else
  Post.all.order('created_at DESC')
  end

但是在我添加了 trix 编辑器后,帖子内容搜索停止工作(对于标题 - 有效)

ruby-on-rails ruby trix
1个回答
0
投票

老问题,但如果有人仍然感兴趣:

t = "%#{search}%"
post_ids = ActionText::RichText
    .where(record_type: "Post")
    .where(name: "content")
    .where("body ILIKE ?", t)
    .pluck(:record_id)
Post.where(id: post_ids)

或者直接在模型上结合字段搜索:

Post.where(id: post_ids).or(Post.where("title ILIKE ?", t))
© www.soinside.com 2019 - 2024. All rights reserved.