Home Filter posts when clicking in a link tag
Reply: 0

Filter posts when clicking in a link tag

user2165 Published in August 15, 2018, 11:15 am

I have a Post with a relationship has_belongs_to_many with the model Tag. post.rb

class Post < ActiveRecord::Base
  has_and_belongs_to_many :tags, uniq: true

  scope :where_tag, ->(term) { select('posts.id, posts.title').joins(:tags).where('tags.name == ?', "#{term}") }


class Tag < ActiveRecord::Base end

on rails console I can do a search for the posts who have this tag:

> ap p = Post.where_tag('minho')
   (0.2ms)  SELECT COUNT(*) FROM "posts" INNER JOIN "posts_tags" ON "posts_tags"."post_id" = "posts"."id" INNER JOIN "tags" ON "tags"."id" = "posts_tags"."tag_id" WHERE (tags.name == 'minho')
  Post Load (0.2ms)  SELECT posts.id, posts.title FROM "posts" INNER JOIN "posts_tags" ON "posts_tags"."post_id" = "posts"."id" INNER JOIN "tags" ON "tags"."id" = "posts_tags"."tag_id" WHERE (tags.name == 'minho')
    [0] #<Post:0x007f91d9d5af58> {
           "id" => 7,
        "title" => "Romenig Lima Damasio"
    [1] #<Post:0x007f91d9d5ad78> {
           "id" => 6,
        "title" => "Brave browser"
=> nil

I would like to put filter this posts when the user clicks the respective tag. So in views/tags/_tag.html.slim I put

= link_to tag.name, search_by_tag_posts_path

PostController I create this method:

      def search_by_tag
        @tag = Tag.find(params[:tag_id])
        @posts = policy_scope(Post.where_tag(@tag.name))
        render action: :index

and in routes:

resources :posts, only: [:index, :show, :edit, :update] do
    collection do
       get :search_by_tag

But when I run rails server and try when clicking the tag I get this error:

ActiveRecord::RecordNotFound in PostsController#search_by_tag
Couldn't find Tag with 'id'=
Extracted source (around line #72):
71 def search_by_tag
72  @tag = Tag.find(params[:tag_id])

What I'm doing bad, it has another way to do this? This scope is a good idea?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.324374 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO