acts_as_taggable_onを用いてpostに紐づいたタグ機能を実装しています。
そこで、一つ質問です。
acts_as_taggable_onで生成したtagsのshow.html.erb(例:../tags/タグ1)に該当タグ(ここではタグ1)と紐づいているpostへのテキストリンクを作成することは可能でしょうか?
tagsの一覧を表示することまではできた(tagsのindexページ)のですが、show.html.erbページに紐づいているpostテキストリンクを生成することができません。
postとtagで親子関係を作らないといけないのでしょうか?
以下は該当コードです。
ご教授ください。
tags_controller.rb
def show #@tag = ActsAsTaggableOn::Tag.find(params[:id]) @tag=ActsAsTaggableOn::Tag.find_by(name: params[:name]) @posts = Post.tagged_with(@tag.name) end
tags show.html.erb
<h1><%= @tag.name %></h1><%= link_to "タグ一覧",tags_path %> <div><%= render @posts %></div>
post.rb
acts_as_taggable_on :tags acts_as_taggable after_validation :save_tags 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
#追記
routes.rb
Rails.application.routes.draw do root 'static_pages#home' get '/about' => 'static_pages#about' get '/contact' => 'static_pages#contact' resources :categories do resources :posts end resources :posts do resources :comments resources :tags end get 'tags/:name' => 'tags#show' resources :tags, only: [:index, :show] end
あなたの回答
tips
プレビュー