Regarding ruby on rails, regarding the search for activerecord using ransack.

Asked 2 years ago, Updated 2 years ago, 97 views

What do you want to solve

We are implementing a soccer player search function using ransack.
Search by keyword is successful, but activecord cannot be searched
The form data is going well, but I don't know where to go.

Problems/errors encountered

<%=search_form_for@q,url:search_items_pathdo|f|%>
<%=f.label:name_cont, 'Search Players' %>
<%=f.search_field:name_cont%>
<%f.label:category_id%>
<%=f.collection_select(:category_id, Category.all, :id, :name, {}, {class:"select-box", id:"category"})%>
<%f.label:country_id%>
<%=f.collection_select(:country_id, Country.all, :id, :name, {}, {class:"select-box", id:"country"})%>
<br>
<%=f.submit 'Search'%>
<%end%>

This is the code in question
If you only put keywords in the name

Parameters:{"q"=>{"name_cont"=>"Messi", "category_id"=>"0", "country_id"=>"0"}, "commit"=>"search"}

This is how the search succeeds, but if you enter a keyword from activaterecord,

Parameters: {"q"=>{"name_cont"=>"", "category_id"=>"1", "country_id"=>"0"}, "commit"=>"search"}

Search fails in this case
If you add _cont to all activecords, the search will fail even if the name keyword is entered.

The behavior is the same when you search only for categories and when you search without any characters.
That's why I think there's something missing to receive the category id.
The model is
The item is

class Item<ApplicationRecord
extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to —category
belongs_to —minicategory
belongs_to —brand
end

Category is

class Category<ActiveHash::Base
include ActiveHash::Associations
has_many —Items

self.data = [
{ id:0, name: 'Select Category'},
{ id:1, name: 'Keeper',
{ id:2,name:'striker'},
]
end

The player column is

 id, name, category_id, country_id

Category and country are implemented in activerecord.

Parameters: {"q"=>{"name_cont"=>"", "category_id"=>"1", "country_id"=>"0"}, "commit"=>"search"}

If the parameter name is empty and there is a count or category number, then the count matches.I think this is an implementation of a partial match search because I would like to display the name, category, or country if they match.

ruby-on-rails ruby rubygems

2022-09-30 18:19

1 Answers

If you want to search category_id or country_id for exact matches because https://github.com/activerecord-hackery/ransack#search-matchers does not have a predicate of *_id, the parameter is not q[category_id] or Shouldn't it be gory_id_eq] or q[country_id_eq]?

<%f.label:category_id_eq%>
<%=f.collection_select(:category_id_eq, Category.all, :id, :name, {}, {class: "select-box", id: "category"})%>
<%f.label:country_id_eq%>
<%=f.collection_select(:country_id_eq, Country.all, :id, :name, {}, {class:"select-box", id:"country"})%>


2022-09-30 18:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.