I read and summarized github on my own about ransack, which is often used to implement search functions.
Ransack enables the creation of both simple and advanced search forms for your Ruby on Rails application (demo source code here).
ransack allows you to create simple and advanced forms in Ruby on Rails.
First install ransack
gem 'ransack'
- The default param key for search params is now :q
2.form_for is now search_form_for
Currently I am using search_form_for instead of form_for.
3.you will get your search results (an ActiveRecord::Relation in the case of the ActiveRecord adapter) via a call to Ransack#result.
Search results can be obtained by calling the result method.
Let's create a controller based on the above.
Search parameter: Search using q and Then I got the result by .result.
controller.rb
def index
@q = Person.ransack(params[:q])
@people = @q.result(distinct: true)
end
The view looks like this: It uses the search_form_for helper and the search parameter q. search_field is the field to be searched.
form.html
<%= search_form_for @q do |f| %>
# Search if the name field contains...
<%= f.label :name_cont %>
<%= f.search_field :name_cont %>
# Search if an associated articles.title starts with...
<%= f.label :articles_title_start %>
<%= f.search_field :articles_title_start %>
# Attributes may be chained. Search multiple attributes for one value...
<%= f.label :name_or_description_or_email_or_articles_title_cont %>
<%= f.search_field :name_or_description_or_email_or_articles_title_cont %>
<%= f.submit %>
<% end %>
In the above example <% = f.search_field: name_cont%> And so on, _cont was written after name. It's looking for a partial match for name. What else is there I've listed some.
retrieval method | meaning |
---|---|
*_eq | equal |
*_not__eq | different |
*_lt | Smaller |
*_lteq | Less than |
*_gt | Greater |
*_gteq | that's all |
*_cont | Partial Match |
*_start | *Begins with |
*_end | *end with |
There are still more functions, but today, in a place like this Don't get tired of reading English ...
** 78 days to become a full-fledged engineer **
Recommended Posts