LoginSignup
2
2

More than 3 years have passed since last update.

acts-as-taggable-onを使って絞り込み機能を作る

Last updated at Posted at 2020-07-04

環境

  • ubuntu(WSL)
  • rails 6.0.3

事前準備

以下の機能は作成済みとします。

  • 投稿機能
  • 投稿詳細
  • gemのインストール
  • テーブルの作成
  • ransackの導入

手順

  • タグの保存
  • ビューで表示
  • 絞り込みの実装

タグの保存

タグをつけたいモデルに以下を追加。

micropost.rb
acts_as_taggable

保存するためにストロングパラメータに以下を追加。
念のためcreateも載せておきます。

microposts_controller.rb
 def create
    @micropost = Micropost.new(micropost_params.merge(user_id: current_user.id))
    if @micropost.save
      redirect_to @micropost, flash:{success: "投稿しました"}
    else
      render :new
    end
 end

 def show
    @micropost = Micropost.find(params[:id])
 end

 private

 def micropost_params
   params.require(:micropost).permit(:content, :image, :tag_list)
 end

ビューの作成と表示

ビューに以下を追加してください。
入力ビューと表示ビューを作ります。

new.html.slim
= form_with model:  micropost, local: true do |f|
  .form-group
    = f.label :tag
    //,で区切る
    = f.text_field :tag_list, value: @micropost.tag_list.join(","), class: "form-control"
  = f.submit "送信", class: "btn btn-primary"
show.html.slim
table.table.table-hover
    today
      tr
        th = Micropost.human_attribute_name(:tag)
        td
          - @micropost.tag_list.each do |tag|
            = link_to tag, microposts_path(tag_name: tag), class: "micropost_tags__link"

絞り込み機能の実装

microposts_controller.rb
  def index
    @q = Micropost.ransack(params[:q])
    if params[:tag_name]
      #選択した同じ投稿の情報を返す
      @microposts = Micropost.tagged_with(params[:tag_name]).page(params[:page])
    elsif params[:q]
      #投稿を一覧を返す
      @microposts = @q.result(distinct: true).page(params[:page])
    else
      @microposts = Micropost.page(params[:page])
    end
  end

終わりに

間違いがありましたら編集リクエストまたはコメントお願いします。

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