[Ruby] Create a narrowing function using acts-as-taggable-on

1 minute read

Environment

  • ubuntu (WSL)
  • rails 6.0.3

Advance preparation

The following functions have been created.

  • Post function
  • Post details
  • gem installation
  • Create table
  • Introduction of ransack

Procedure

  • Save tag
  • Show in view
  • Implementation of narrowing down

Save tag

Add the following to the model you want to tag.

micropost.rb


acts_as_taggable

Added the following to the strong parameters to save. Just in case, I’ll post create as well.

microposts_controller.rb


 def create
    @micropost = Micropost.new(micropost_params.merge(user_id: current_user.id))
    if @micropost.save
      redirect_to @micropost, flash:{success: "Posted"}
    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

Creating and displaying views

Add the following to your view: Create an input view and a display view.

new.html.slim


= form_with model: micropost, local: true do |f|
  .form-group
    = f.label :tag
    Separate with //,
    = f.text_field :tag_list, value: @micropost.tag_list.join(","), class: "form-control"
  = f.submit "send", class: "btn btn-primary"

show.html.slim


table.table.table-hover
    today
      tr
        th = Micropost.human_attribute_name(:tag)
        td
          [email protected]_list.each do |tag|
            = link_to tag, microposts_path(tag_name: tag), class: "micropost_tags__link"

Implementation of narrowing function

microposts_controller.rb


  def index
    @q = Micropost.ransack(params[:q])
    if params[:tag_name]
  #Return info for same post selected
      @microposts = Micropost.tagged_with(params[:tag_name]).page(params[:page])
    elsif params[:q]
  # Return list of posts
      @microposts = @q.result(distinct: true).page(params[:page])
    else
      @microposts = Micropost.page(params[:page])
    end
  end

At the end

If you make a mistake, please make an edit request or comment.