So I have acts_as_taggable working properly. I am able to add the tags when creating a new post and I can see all the tags when looking at the posts. What Im trying to do is create a nav link for certain tags. For instance I want a nav link that says "Movies" and when I click that link I want all the posts that I have created that have the tag "Movies" to show. This is my post_controller.rb
def index
@posts = current_author.posts.most_recent
end
def show
end
def new
@post = current_author.posts.new
end
private
def set_post
@post = current_author.posts.friendly.find(params[:id])
end
def post_params
params.require(:post).permit(:title, :body, :description, :banner_image_url, :tag_list)
end
end
end
My post.rb that deals with the tags
acts_as_taggable # Alias for acts_as_taggable_on :tags
extend FriendlyId
friendly_id :title, use: :slugged
belongs_to :author
scope :most_recent, -> { order(published_at: :desc) }
scope :published, -> { where(published: true) }
scope :with_tag, -> (tag) { tagged_with(tag) if tag.present? }
scope :list_for, -> (page, tag) do
recent_paginated(page).with_tag(tag)
end
You can create a custom route which the nav button can link to.
<%= link_to "Movies, tagged_posts_path("Movies") %>
In posts_controller, create a method for the custom route. The custom route can use the 'with_tag' scope to return only posts tagged with 'Movies' to your view.
def tagged
@posts = Post.with_tag(params[:tag])
end
Make sure you add the new custom route to the routes file.
resources :posts do
collection do
get "/tagged/:tag", to: "posts#tagged", as: "tagged"
end
end