Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails joins query

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.

like image 397
1dolinski Avatar asked Feb 07 '26 14:02

1dolinski


1 Answers

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

@post = Post.joins(:taggings).where(taggings: {tag_id: 17})
like image 66
Raphael Abreu Avatar answered Feb 09 '26 09:02

Raphael Abreu