It is a gem for implementing the search function for rails
.
Get data linked based on search keywords
On the contrary, if there is no keyword, all are acquired.
Write ransack
in Gemfile and bundle install
Gemfile
gem 'ransack'
Terminal
bundle install
next
Write the process to use the function of ransack
in the controller.
app/controllers/users_controller.rb
class UsersController < ApplicationController
def index
@q = User.ransack(params[:q])
@users = @q.result
#Returns the result with the result method
end
end
next
Write a search form in the view file.
Search forms using ransack
use a helper method called search_form_for
.
:app/views/users/index.html.erb
<%= search_form_for @q do |f| %>
<div class="d-flex">
<div class="form-group flex-grow-1">
#search window
<%= f.search_field :name_cont, placeholder: "Find 〇〇", class: "form-control" %>
</div>
<div>
#Search
<%= f.submit "Search", class: "btn btn-primary ml-1" %>
</div>
</div>
<% end %>
This time, the purpose is "partial match search", so it is set to column name_cont
.
For "match search", use column name_eq
.
The search function is ready!
It's a rough content, but Conclusion Thanks to the engineers who made the groundbreaking gem! : joy:
Recommended Posts