Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search text in ActionText attribute

I have a Post model and this model uses ActionText for the attribute content:

has_rich_text :content

Now I have a simple search and I would like to search for text inside content, so I have something like this:

@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}%")

But this gives an error:

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

What is the correct way to search for text in an ActionText attribute?

like image 727
John Avatar asked Jan 03 '20 08:01

John


2 Answers

This is the migration generated by 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

It tells us that the contents is stored in action_text_rich_texts and that it uses a polymorphic association to link to the record.

So you need to provide both the type and id in the join as there can be multiple rows with the same id but for different models:

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

You can just setup an association through so you don't have to join manually:

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

The whole query reads:

@posts = Post.joins(:action_text_rich_text)
             .where("action_text_rich_texts.body LIKE ?", "%#{search_text}%")
like image 178
max Avatar answered Oct 23 '22 01:10

max


Thanks, Max, I have been struggling with this all day using Ransack.

So I added:

has_one :action_text_rich_text, class_name: 'ActionText::RichText', as: :record

And then used _or_action_text_rich_text_body_ in my search field and it worked like a charm.

like image 4
RCarter Avatar answered Oct 23 '22 01:10

RCarter