Help us understand the problem. What is going on with this article?

[Rails]ransackを使わずに検索機能の実装

実装すること

投稿(Item)のタイトル(title)の検索

モデルの作成

$ rails g model Item title:string
$ rails db:migrate

ルーティングの作成

config/routes.rb
Rails.application.routes.draw do

    get "search" => "items#search", as: 'search'

end

Itemコントローラーの作成・編集

$ rails g controller items
app/controllers/items_controller.rb
class ItemsController < ApplicationController

    def search
        #itemのtitleを曖昧検索
        @items = Item.where('items.title LIKE(?)', "%#{params[:search]}%").order(created_at: :desc)
        #フォームに入力した内容を取ってくる
        @search_result = "#{params[:search]}"
    end
end

ビューの編集

投稿一覧

検索フォームはパーシャルにします。

app/views/items/index.html
<div class="search">
    <%= render 'items/search_form' %>
</div>

検索フォーム

app/views/items/_search_form.html
<%= form_tag(users_search_path, :method => 'get') do %>
    <%= text_field_tag :search, params[:search], class: "form-control", id: "search_area", placeholder: "タイトルを入力"%>
    <%= submit_tag '検索' %>
<% end %>

検索結果

app/views/items/search.html
<h2>タイトル"<%= @search_result %>"の検索結果(<%= @items.count %>件)</h2>
<% @items.each do |item| %>
    <%= item.title %>
<% end %>

最後に

最後までご覧いただきありがとうございます。
初学者ですので間違っていたり、分かりづらい部分もあるかと思います。
何かお気付きの点がございましたら、お気軽にコメントいただけると幸いです。
Twitter:https://twitter.com/yto_oct
note:https://note.com/yto_oty

参考

gemを使わずに検索機能を作ろう!複数テーブルの検索にも対応可能!
https://qiita.com/chain_saw_man/items/07faf8fed3224c1dccfb
Ruby on Rails 検索機能拡張 (railsチュートリアル)
https://qiita.com/mochikichi321/items/5c9630c5d87b47130942

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした