This time, I will introduce how to implement the search function in Rails.
--Explain as a function to search articles on blog sites --The article table is posts --Post columns are title and body --Display search form and search results on the article list screen (index.html.erb)
routes.rb
get 'search' => 'posts#search'
html:index.html.erb
<div class="search-form">
<%= form_with url: search_path, method: :get, local: true do |f| %>
<%= f.text_field :keyword, value: @keyword %>
<%= f.submit "Search" %>
<% end %>
</div>
<div class="post-list">
<% @posts.each do |post| %>
<%= post.title %>
<% end %>
</div>
Describe the following in post.rb.
post.rb
def self.search(keyword)
where(["title like? OR body like?", "%#{keyword}%", "%#{keyword}%"])
end
OR outputs the article if the search keyword partially matches either title or body. (Use AND if you want to output only when both title and body are hit.)
posts_controller.rb
def search
@posts = Post.search(params[:keyword])
@keyword = params[:keyword]
render "index"
end
This completes the search function.
-[Rails] How to search across multiple columns with one search form
https://qiita.com/bSRATulen2N90kL/items/6a7c99bf3641ac6838fb
Recommended Posts