[Ruby on Rails] Search function (not selected)

Target

search.gif

Development environment

ruby 2.5.7 Rails 5.2.4.3 OS: macOS Catalina

Premise

[Ruby on Rails] Search function (model, method selection formula) After implementing this, we will edit it.

flow

1 Edit controller 2 Edit view

Editing controller

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

edit view

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 %>
Supplement [In error] Routing and partial templates [[Ruby on Rails] Search function (model, method selection formula)](https://qiita.com/japwork/items/e6ee225970b50ea5d796) Please refer to here.
Supplement [About present and empty] [nil? empty? blank? present? exists? Let's use the method properly according to the situation [Rails]](https://qiita.com/takuyanin/items/aa8c1d82ab14f1827a6a) It was explained in an easy-to-understand manner here.
Supplement [About &&] [Ruby and,&&And or,||Differences and precautions](https://qiita.com/riku-shiru/items/533a01bdf18e2e3eef46) It was explained in an easy-to-understand manner here.

Recommended Posts