1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

検索機能とタグ検索の両立

Posted at

今日は検索機能とタグ検索の両立についてまとめます!

この検索機能の記事を実装できていることを前提とします!
https://qiita.com/Kairi_Yasunnde/items/935dcdb8ec88b9ed9d91#3タグ検索機能の実装

tweet.controller.rb

  def index
      if params[:search].blank? && params[:tag_id].blank?
      @tweets= Tweet.all
    elsif params[:search].present? && params[:tag_id].blank?
      @tweets= Tweet.where("body LIKE ?",'%' + params[:search] + '%')
    elsif params[:search].blank? && params[:tag_id].present?
      @tweets = Tag.find(params[:tag_id]).tweets
    else
      @tweets = Tag.find(params[:tag_id]).tweets.where("body LIKE ? ",'%' + params[:search] + '%') 
    end
index.html.erb
 <<%= form_tag({controller:"tweets",action:"index"},method: :get)do %>
 <%= text_field_tag :search %>
 
  <%= select_tag :tag_id,
  options_from_collection_for_select(Tag.all, :id, :name, params[:tag_id]),
  {
   prompt: 'タグで絞り込み',
   
  }%>
  
 <%= submit_tag '検索する' %>
<% end %>

この二つのページを挿入すれば、タグ検索と通常の検索機能を両立可能です!
カラムの違う部分などは都度調整してくださいね!

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?