Yurii
Yurii

Reputation: 53

How to search in rails 7 with ransack when action text rich text using in the Post model?

Could somebody help me to figure out why it is not working? So what is the story: there is a rails 7 (7.1.3) blog app with a ransack version 4.1.1

In the search form, I need to search text by the post title and by the post body and I get this error

undefined method `type' for nil:NilClass

in the params I can see this

Parameters:

{"q"=>{"title_or_body_cont"=>"should"}, "commit"=>"Search"}

When I am trying to search only with a title like title_cont everything is ok, but when searching with body_cont or title_or_body_cont get the mentioned error. I think that is because the Post model does not have a body field and this field is in the action_text_rich_texts table. And after adding an association on the action_text_rich_texts table in the Post model I still have the mentioned error. I would appreciate for your help.

and my code

class Post < ApplicationRecord
  has_rich_text :body
  has_many :comments, dependent: :destroy
  belongs_to :user
  has_one_attached :post_image

  validates :title, presence: { message: 'must be given please' }, length: { minimum: 5 }
  validates :body, presence: true, length: { minimum: 10 }
  validate :post_body_length
  validate :acceptable_image

  def self.ransackable_attributes(_auth_object = nil)
    %w[title body created_at updated_at user_id]
  end

  def self.ransackable_associations(_auth_object = nil)
    %w[users action_text_rich_texts]
  end

  private

  def acceptable_image
    return unless post_image.attached?

    errors.add(:post_image, 'is too big') unless post_image.blob.byte_size <= 5.megabyte

    acceptable_types = ['image/jpeg', 'image/png']
    return if acceptable_types.include?(post_image.content_type)

    errors.add(:post_image, 'must be a JPEG or PNG')
  end

  def post_body_cant_be_empty
    if self.body.blank?
      self.errors.add(:body, "can't be empty")
    end
  end

  def post_body_length
    if self.body.to_plain_text.length < 10
      self.errors.add(:body, 'is too short (minimum is 10 characters)')
    end
  end
end

also, there is a searches_controller

class SearchesController < ApplicationController
  def index
    @query = Post.ransack(params[:q])
    @posts = @query.result.includes(:rich_text_body)
  end
end

and a search_form

<%= search_form_for @query, url: searches_path, method: :get, html: { class: "d-flex", role: "search" } do |f| %>
  <%= f.search_field :title_or_body_cont, class: "form-control me-2", placeholder: "Search title or body..." %>
  <%= f.submit "Search", class: "btn btn-outline-secondary-light btn-sm" %>
<% end %>

and routes

resources :searches, only: %i[index]

Post table structure

 create_table "posts", force: :cascade do |t|
    t.string "title", null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.bigint "user_id", null: false
    t.index ["user_id"], name: "index_posts_on_user_id"
  end

Action_text_rich_texts table structure

create_table "action_text_rich_texts", force: :cascade do |t|
    t.string "name", null: false
    t.text "body"
    t.string "record_type", null: false
    t.bigint "record_id", null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["record_type", "record_id", "name"], name: "index_action_text_rich_texts_uniqueness", unique: true
  end

Upvotes: 0

Views: 247

Answers (1)

Yurii
Yurii

Reputation: 53

Thanks for your suggestions. It works.

I add the association rich_text_body in the Post model to the method self.ransackable_associations

def self.ransackable_associations(_auth_object = nil)
   %w[users rich_text_body]
end

and in the search form search_field fix places where to search

title_or_rich_text_body_body_cont

After making this adjustment, everything is functioning properly.

also need to add ransack initializer according to this suggestion ransack upgrade to 4.0.0 and ActionText::RichText

class ActionText::Record < ActiveRecord::Base
  def self.ransackable_attributes(auth_object = nil)
    authorizable_ransackable_attributes
  end
end

Upvotes: 1

Related Questions