When creating a personal application, implement a search function so that the content of posted articles can be displayed by searching.
This time, we will not transition to the page by specifying: id, so we will use collection to set the routing.
routes.rb
resources :posts do
get :search, on: :collection
resource :likes, only: [:create, :destroy] -Like function implementation
end
** LIKE clause ** The LIKE clause allows you to search for strings. Used with the where method.
Execution example | Details |
---|---|
where('title LIKE(?)', "a%") | Titles starting with a |
where('title LIKE(?)', "%b") | Titles ending in b |
where('title LIKE(?)', "%c%") | Titles containing c |
where('title LIKE(?)', "d_") | Two-letter title starting with d |
where('title LIKE(?)', "_e") | Two-letter title ending in e |
app/models/post.rb
def self.search(search)
return Post.all unless search
Post.where('body LIKE(?)', "%#{search}%")
end
post_controller.rb
def search
@posts = Post.search(params[:keyword])
end
It is assumed that you are doing a partial template using the ** render method **. ** post ** to the right of {post: post} is ** post ** as a variable in each method, indicating an instance of ** post **. The ** post ** on the left represents the name of the variable in the partial template.
search.html.erb
<% @posts.each do |post| %>
<%= render partial: "post", locals: { post: post } %>
<% end %>
The implementation of the search function was completed relatively easily. I will implement other functions and increase what I can do. Thank you for watching to the end: grin:
Recommended Posts