Ransack, unable to search two attributes

2.1k Views Asked by At

I'm a beginner trying to make a searchbar, i'm with a simple attribute research, works fine, but when i try to add another attribute in the search_field, i have an error : "Ransack needs Product associations explicitly allowlisted as searchable. Define a ransackable_associations class method in your Product", but it's here !!

Here under my controller


    class SearchController < ApplicationController
      def index
        @q = Product.ransack(params[:q])
        @products2 = @q.result(distinct: true)
      end
    end

Here the model

    class Product < ApplicationRecord
      belongs_to :category
      has_many :product_carts
      has_many :carts, through: :product_carts

      def self.ransackable_attributes(auth_object = nil)
        ["description", "price", "title"]
      end
      end

and here two tested views that work

the tested views, this two are ok with single term description search

    <%= search_form_for(@q, url: search_path, method: :get, class:"d- 
   flex") do |f| %>
      <%= f.search_field :title_cont, placeholder: "recherchez dans la 
    description", class: "form-control me-2" %>
      <%= f.submit "Ok !" %>
    <% end %>
    <%= search_form_for(@q, url: search_path, method: :get, class:"d- 
   flex") do |f| %>
      <%= f.search_field :description_cont, placeholder: "recherchez dans la 
    description", class: "form-control me-2" %>
      <%= f.submit "Ok !" %>
    <% end %>

BUT this one doesn't want to work, title and description are in the same sqlpostgre product table, just two columns, title is a string and description a text: i have reviewed lots of stackoverflow topics but i cant find any clear manner to resolve this !

    <%= search_form_for(@q, url: search_path, method: :get, class:"d- 
   flex") do |f| %>
      <%= f.search_field :description_or_title_cont, placeholder: "recherchez dans la 
    description", class: "form-control me-2" %>
      <%= f.submit "Ok !" %>
    <% end %>

rails error

i tried other searches with tchat gpt who told me to try this in the model but still the same error

tchat gpt

Thanks in advance for your help !

1

There are 1 best solutions below

0
Erwin Agüero On

Hello @samuel bellotlecoq, apologies, but I am not able to find your method ransackable_associations. I had the same problem, and given I just wanted to search by the fields in the model (your case is Product), I define the following methods in my model:

class << self
  def ransackable_attributes(auth_object = nil)
    [ "id","name" ]
  end

  def ransackable_associations(auth_object = nil)
   []
  end

end

If you look in the code base here, you can identify that the method needs to be defined.

I hope my answer can help you.