ruby 2.5.7 Rails 5.2.4.3 OS: macOS Catalina
[Ruby on Rails] Search function (model, method selection formula) After implementing this, we will edit it.
1 Edit controller 2 Edit view
This time we are focusing on ambiguous searches. If you want an exact match where(name: @content) It will be.
app/controllers/searchs_controller.rb
class SearchsController < ApplicationController
def search
@content = params["content"]
@users = User.where('name LIKE ?', '%'+@content+'%')
@posts = Post.where('title LIKE ?', '%'+@content+'%')
end
end
erb:app/views/search.html.erb
<% if @users.present? && @posts.present? %>
<h3>【Users,Posts model search results] Search word:<%= @content %></h3>
<h4>·username</h4>
<%= render 'users/index', users: @users %>
<h4>・ Posted content</h4>
<%= render 'posts/index', posts: @posts %>
<% elsif @users.present? && @posts.empty? %>
<h3>[Users model search results] Search word:<%= @content %></h3>
<h4>·username</h4>
<%= render 'users/index', users: @users %>
<% elsif @users.empty? && @posts.present? %>
<h3>[Posts model search results] Search word:<%= @content %></h3>
<h4>・ Posted content</h4>
<%= render 'posts/index', posts: @posts %>
<% else %>
<h3>Search word:<%= @content %>Not applicable to</h3>
<% end %>
Recommended Posts