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?
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}%")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With