Arif Arif - 2 months ago 12
Ruby Question

ActiveRecord querying through multiple joins

So below are my models:

post.rb

class Post < ActiveRecord::Base
has_many :taggings
has_many :tags, through: :taggings
has_many :collectables
has_many :collections, through: :collectables
end


tagging.rb

class Tagging < ActiveRecord::Base
belongs_to :post
belongs_to :tag, counter_cache: :posts_count
end


tag.rb

class Tag < ActiveRecord::Base
has_many :taggings
has_many :posts, through: :taggings
end


collectable.rb

class Collectable < ActiveRecord::Base
belongs_to :post
belongs_to :collection, counter_cache: :posts_count
end


collection.rb

class Collection < ActiveRecord::Base
has_many :collectables
has_many :posts
end


A Collection has many Posts, and a Post has many Tags. Now I'm trying to create a search bar that'll search for Collections by Posts that have particular Tags (
tag.name
is the search term). For instance, Collection 1 has a post that has the tag #cat. Now if the user searches for "cat", Collection 1 will show up in the results. I'm not sure how the query should look like for making this happen.

def self.search(search)
Collection.joins(:posts) ... ?
end

Answer

try this:

def self.search(search)
  Collection.includes(posts: :tags).where(tags: {name: search})
end