はじめまして、プログラムを勉強しはじめて2ヶ月半が経とうとしている学生です。
以前以下の質問でacts_as_taggableを用いたタグ機能の実装について質問しました(moke様ご回答ありがとうございます!)
https://teratail.com/questions/67602
現在掲示板を作成しております。そこでtag機能を実装しているのですが、tags/show.html.erbでうまく関連するpostを紐づけることができません。
実装したい内容は該当tagを有するpostをtags/show.html.erbにてpostへのリンクとともにリストアップすることです。
何かしらの解決方法がありましたらご教授をいただきたいです!
posts/show.html.erb
<strong>タグ:</strong> <% @post.save_tags %> <%= @post.tag_list.map{|tag|link_to(tag,"/tags/#{tag}")}.join(",").html_safe %>
tags_controller.rb
class TagsController < ApplicationController def show @tag=ActsAsTaggableOn::Tag.find_by(name: params[:name]) @posts = Post.tagged_with(@tag.name) end end
routes.rb
#該当部分のみ resources :posts do resources :comments resources :tags end get 'tags/:name' => 'tags#show' resources :tags, only: [:index, :show]
#追記
post.rb
def save_tags array = self.check_taggable_word(self.title) self.tag_list.add(array, parse: true) #self.save end def tag_lists tag_lists = self.tag_list end def check_taggable_word(text) ary = Array.new nm = Natto::MeCab.new nm.parse(text) do |n| ary<<n.surface end #mekabuで要素に分解 tags = ActsAsTaggableOn::Tag.pluck(:name) #タグを取得 return ary & tags #共通部分を返す end
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/03/10 05:55
2017/03/10 07:19 編集
2017/03/10 08:58
2017/03/10 09:00
2017/03/10 09:36
2017/03/11 02:56
2017/03/11 03:07
2017/03/12 05:46
2017/03/12 10:23 編集
2017/03/12 16:39