The following functions are assumed to have been created.
--Posting function --Post details --Install gem --Create table --Introduction of ransack
--Save tags --Display in view --Implementation of narrowing down
Add the following to the model you want to tag.
micropost.rb
acts_as_taggable
Add the following to the strong parameters to save. I will also post create just in case.
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
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
//,Separated by
= 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
- @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]
#Returns information for the same selected post
@microposts = Micropost.tagged_with(params[:tag_name]).page(params[:page])
elsif params[:q]
#Return a list of posts
@microposts = @q.result(distinct: true).page(params[:page])
else
@microposts = Micropost.page(params[:page])
end
end
If you make a mistake, please make an edit request or comment.
Recommended Posts