ruby-on-rails 在“文本”属性中搜索文本

q9rjltbz  于 2023-11-20  发布在  Ruby
关注(0)|答案(3)|浏览(141)

我有一个Post模型,这个模型使用了content属性的文本:

has_rich_text :content

字符串
现在我有一个简单的搜索,我想搜索content中的文本,所以我有这样的东西:

@posts = Post.joins("INNER JOIN action_text_rich_texts ON action_text_rich_texts.record_id = posts.id").where("action_text_rich_texts.content LIKE ?", "%#{search_text}%")


但这给出了一个错误:

PG::UndefinedColumn: ERROR:  column action_text_rich_texts.content does not exist


在“文本”属性中搜索文本的正确方法是什么?

50pmv0ei

50pmv0ei1#

以下是rails action_text:install生成的迁移:

# This migration comes from action_text (originally 20180528164100)
class CreateActionTextTables < ActiveRecord::Migration[6.0]
  def change
    create_table :action_text_rich_texts do |t|
      t.string     :name, null: false
      t.text       :body, size: :long
      t.references :record, null: false, polymorphic: true, index: false
      t.timestamps

      t.index [ :record_type, :record_id, :name ], name: "index_action_text_rich_texts_uniqueness", unique: true
    end
  end
end

字符串
它告诉我们内容存储在action_text_rich_texts中,并且它使用多态关联来链接到记录。
所以你需要在join中同时提供type和id,因为可能有多个行具有相同的id,但用于不同的模型:

@posts = Post.joins("INNER JOIN action_text_rich_texts ON action_text_rich_texts.record_id = posts.id AND record_type = 'Post'")


您只需通过设置一个关联,就不必手动加入:

class Post < ApplicationRecord
  has_rich_text :content
  # used to query the attached ActionText directly
  has_one :action_text_rich_text,
    class_name: 'ActionText::RichText',
    as: :record
end


整个查询内容如下:

@posts = Post.joins(:action_text_rich_text)
             .where("action_text_rich_texts.body LIKE ?", "%#{search_text}%")

ruyhziif

ruyhziif2#

谢谢你,Max,我一整天都在用Ransack解决这个问题。
所以我补充说:
has_one:action_text_rich_text,class_name:'文本::RichText',as::record
然后在我的搜索字段中使用_or_action_text_rich_text_body_,它就像一个魅力。

bkkx9g8r

bkkx9g8r3#

class Post < ApplicationRecord
  has_rich_text :content
end

字符串
Rails会自动添加一个has_one关联rich_text_#{name}

>> Product.reflections["rich_text_content"]
=>
#<ActiveRecord::Reflection::HasOneReflection:0x00007f3a8071b1e8
 @active_record=
  Product(id: integer),
 @active_record_primary_key="id",
 @class_name="ActionText::RichText",
 @foreign_key="record_id",
 @inverse_name=:record,
 @name=:rich_text_content,
 @options={:class_name=>"ActionText::RichText", :as=>:record, :inverse_of=>:record, :autosave=>true, :dependent=>:destroy},
...


您可以使用它来连接和搜索action_text_rich_texts表:

Product.joins(:rich_text_content)
  .where("action_text_rich_texts.body ILIKE ?", "%search something%")

相关问题