LoginSignup
0
0

More than 1 year has passed since last update.

【Railsチュートリアル】ユーザー検索機能の実装

Last updated at Posted at 2021-11-28

はじめに

前回の記事【Railsチュートリアル】いいね機能の実装に引き続きRailsチュートリアル第6版sample_appの機能拡張を進めていく。
今回は以下の様なユーザー検索機能を実装していく。
スクリーンショット 2021-11-28 21.42.28.png

前提
第6版sample_appが完成している

手順

Gemfileにransackを追加

Gemfile
gem 'ransack'

検索フォームを作成

app/views/users/_search_form.html.erb
<%= search_form_for @q do |f| %>
  <%= f.label :name_cont, 'User Search' %>
  <div class="input-group">
    <%= f.text_field :name_cont, placeholder: "Enter username...",
                      class: 'form-control' %>
    <span class="input-group-btn">
     <%= f.submit 'Go', class: "btn btn-primary" %>
    </span>
  </div>
<% end %>

ユーザーコントローラーを変更

app/controllers/users_controller.rb
class UsersController < ApplicationController
  .
  .
  .
  def index
    if params[:q] && params[:q].reject { |key, value| value.blank? }.present?
      @q = User.ransack(search_params, activated_true: true)
      @title = "Search Result"
    else
      @q = User.ransack(activated_true: true)
      @title = "All users"
    end
    @users = @q.result.paginate(page: params[:page])
  end
  .
  .
  .
  private
  .
  .
  .

    def search_params
      params.require(:q).permit(:name_cont)
    end

end

ビューを変更

app/views/users/index.html.erb
<% provide(:title, 'All users') %>
<h1>All users</h1>

<div class="row">
  <div class="search_form">
    <%= render 'users/search_form' %>
  </div>
</div>

<%= will_paginate %>

<% unless @users.empty? %>
  <ul class="users">
    <%= render @users %>
  </ul>
<% else %>
  <p class="search_message">
    Couldn't find any user.
  </p>
<% end %>

<%= will_paginate %>

cssを追加

app/assets/stylesheets/custom.scss
/* search_form */

.search_form {
  overflow: auto;
  margin: 10px;
  float: left;
  .input-group {
    width: 300px;
    .form-control {
      width: 250px;
    }
    .btn {
      width: 50px;
    }
  }
}
.search_message {
  margin-top: 30px;
  font-weight: bold;
  font-size: 1.3em;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0