0

I have three models such as Community, Tagging, and Tag

  • Community belongs_to :tag

  • Tagging has_one :community <= taggable_id will be Community's id

  • Tagging belongs_to :tag

  • Tag has_many :taggings # Tag has 'name' attribute

In this situation, if I had params[:tag], how can I write SQL code to fetch all the communities with tagged by params[:tag]?

5
  • Are you sure a Community is not belonging to Tagging? Commented Jan 30, 2013 at 15:24
  • @MrYoshiji I use the gem called "acts_as_taggable_on_steroid", it's polymorphic so it has taggable_type and taggable_id instead of community_id Commented Jan 30, 2013 at 15:28
  • this gem is pretty old (last date of modification on Github: 2 years ago: github.com/jviney/acts_as_taggable_on_steroids). You should use this one before you get too deep in your implementation: github.com/ivoreis/acts_as_taggable Commented Jan 30, 2013 at 15:30
  • @Mr.Yoshiji sorry about that thats what I'm using now Commented Jan 30, 2013 at 15:34
  • @MrYoshiji The reason why I'm trying to do this with SQL code is, it won't return the community who absolutely has the particular tag. It's really weird. This never happened in development mode :( Commented Jan 30, 2013 at 15:37

1 Answer 1

1

You should be able to see the exact sql generated when you try

 Community.find_tagged_with(params[:tag])

But you should also be able to create the query yourself using the following

 # Rails 3
 Community.joins(taggings: :tag).where(tags: { name: params[:tag] })

 # Rails 2
 Community.all(joins: { taggings: :tag }, conditions: { tags: { name: params[:tag] } })
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks but it's funny that it returns 2 same communities records if the community had tags "apple" and "Apple". one in lower case and another in upper case. Can you restrict this?
I means. I see 2 records of communities in result. But there are the same community.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.