Use Rails form_with to send the information you want to search to the controller and I will write how to implement the function to be listed on the index page.
This time, I will post a post that includes the word I searched for from the Post table in the body I would like to list it in index.html.erb of the Post controller.
[Execution environment] Ruby 2.7.2 Rails 6.0.3.4
erb:search.html.erb
<%= form_with url: posts_path, method: :get, local: true do |f| %>
<%= f.label :post_key, 'Search' %>
<%= f.text_field :post_key %>
<%= f.submit, 'Search for' %>
<% end %>
This time, the search result list will be displayed on the index page, so enter the path corresponding to the index for url. If the page you want to display is different from the index, enter the url corresponding to the page you want to display.
By specifying method as get, it goes through the routing that leads to index and becomes an index action. You can send the value you want to search. If you do not specify this, the method will be sent by post and an error will occur.
Since the value you want to search is stored in: post_key, You can specify any word other than: post_key as long as it is common to the word written in the controller.
posts_controller.rb
def index
if params[:posts_key]
@posts = Post.where(params[:posts_key])
else
@posts = Post.all
end
end
The: posts_key sent from the input form will get you here. The behavior of else is that if you press the search button without entering anything, all posts will be displayed.
erb:index.html.erb
<p>"search results: <%= @posts.count %>Case</p>
<ul class="posts">
<%= @posts.each do |post| %>
<li class="post">
<%= post.content %>
</li>
<% end %>
</ul>
This time I implemented it without using page nation, so The search result list is displayed by executing the iterative process using each method.
The count method is used to display the number of search results.
I think that the search function can be implemented by the above procedure! Feel free to comment if there are any deficiencies or uncertainties I would appreciate it if you could! Thank you for reading until the end!
Recommended Posts