これまでに作った機能について簡単にまとめていく。
今回は、
検索機能の作成
前提条件
一覧画面が作成されていること
使用モデル
Blogモデル
| カラム | データ型 | |
|---|---|---|
| 1 | title | string |
| 2 | content | text |
スコープの作成
app/models/blog.rb
今回は部分一致検索を実装
class Blog < ApplicationRecord
scope :search_by_name, -> (search){where(['name LIKE ?', "%#{search}%"}
end
検索フォームの作成
app/views/blogs/index.html.erb
<%= form_with(model: Blog.new, url: blogs_path, method: :get, local: true) do |f| %> <%= f.label :name %> <%= f.text_field :name %> <%= f.submit '検索', id: 'search_button' %> <% end %>
コントローラーの編集
app/controllers/blogs_controller.rb
class BlogsController < ApplicationController
def index
if params[:blog]
@blogs = Blog.search_by_name(params[:blog][:name])
else
@blogs = Blog.all
end
end
end
以上で作成完了
