<div class="search_field">
<p>Search:</p>
<%= form_tag(posts_path, :method => 'get') do %>
<%= text_field_tag :search, "", {class: "search_field_type"}%>
<%= submit_tag 'Search', :name => nil, class: "search_field_btn" %>
<% end %>
</div>
Please change the path part of form_tag (posts_path,: method =>'get') according to the class name.
post.rb
def self.search(search)
if search
Post.where(["title LIKE ?", "%#{search}%"])
else
Post.all
end
end
Set to hit if the searched character string is applicable even in a part of the title column.
For more information, you can find out what it means by looking at the where clause of SQL.
https://www.wakhok.ac.jp/biblion/1994/DB/subsection2.4.3.5.html
posts_controller.rb
def index
@posts = Post.all.includes(:user).order(id: "DESC").search(params[:search])
end
This will put the articles that hit the search in @posts.
All you have to do is display the list on the View side.
Recommended Posts