3

I have three models

  • Tag => :id, :name
  • Tagging => :id, :tag_id, :post_id
  • Post => :id, :summary

I know the id of the tag. I would like to query for all of the posts that have a specific tag_id, through the Taggings model.

Something like

@post = Post.joins(:taggings).where(:tag_id => 17)

but this doesn't work because it is looking for the tag_id in the Post model and not the Tagging model.

I'm not sure how to do this.

Craig Ringer
  • 307,061
  • 76
  • 688
  • 778
1dolinski
  • 479
  • 3
  • 9
  • 29

4 Answers4

17

I don't like to use string in ActiveRecord queries, so, I prefer this sintax:

@post = Post.joins(:taggings).where(taggings: {tag_id: 17})
Raphael Abreu
  • 211
  • 2
  • 5
  • 2
    You could also add additional conditions after taggings if needed `.where(taggings: {tag_id: 17}, tags: {valid: true})` – icantbecool Mar 14 '17 at 05:32
7

First of all :

 class Post < ActiveRecord::Base

   has_many :taggings
   has_many :tags, :through => :taggings 
 end

 class Taggins < ActiveRecord::Base 
   belongs_to :post 
   belongs_to :tag
 end

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

If you have the tag object you can do

 @posts = @tag.posts 

or

 class Post < .... 
   ....
   def self.find_by_tag_id(tag_id)
      Post.joins(:taggings).where('taggings.tag_id = ?', tag_id)
   end
 end
2

Using the .where format you can pass a string like .where("taggings.tag_id = ?", 17) to qualify the joined taggings table.

Tom Harrison
  • 13,533
  • 3
  • 49
  • 77
1

As @tharrison mentioned. A solution is:

@post = Post.joins(:taggings).where("taggings.tag_id = ?", 17)
Sravan
  • 18,467
  • 3
  • 30
  • 54
1dolinski
  • 479
  • 3
  • 9
  • 29
  • 1
    Just a note here - the first 'taggings' needs to be singular, otherwise you will get the error: `association named not found perhaps misspelled issue in rails association` Reference: http://stackoverflow.com/questions/19231629/association-named-not-found-perhaps-misspelled-issue-in-rails-association – gwalshington Apr 06 '17 at 21:53