Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
3
Help us understand the problem. What is going on with this article?
@yuto_1014

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

More than 1 year has passed since last update.

実装すること

投稿(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

3
Help us understand the problem. What is going on with this article?
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
yuto_1014
ご覧いただきありがとうござます! ≪営業→→Javaエンジニア≫ Ruby,Rails,Java,Spring,cubby,PostgreSQL,MySQL

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
3
Help us understand the problem. What is going on with this article?