Posted By

dima767 on 12/19/07


Tagged

tags groovy grails many-to-many


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

bootz15


Tagging in Grails: many-to-many


 / Published in: Groovy
 

  1. def setup = {
  2. new User(name:'user1').save(flush:true)
  3. new User(name:'user2').save(flush:true)
  4.  
  5. tagsForUser1 = ['tag1','tag2']
  6. tagsForUser2 = ['tag1']
  7.  
  8. u1 = User.findByName('user1')
  9. u2 = User.findByName('user2')
  10.  
  11. //ITEM1 ***************************************************
  12. item1 = new Taggable(name:'item1')
  13. item1.user = u1
  14. tagsForUser1.each {
  15. t = Tag.findByName(it)
  16. if(!t) {
  17. t = new Tag(name:it).save()
  18. }
  19. item1.addToTags(new Tagging(user:u1,tag:t,taggable:item1))
  20. }
  21. item1.save(flush:true)
  22.  
  23. //ITEM2 **************************************************
  24. item2 = new Taggable(name:'item2')
  25. item2.user = u2
  26. tagsForUser2.each {
  27. t = Tag.findByName(it)
  28. if(!t) {
  29. t = new Tag(name:it).save()
  30. }
  31. item2.addToTags(new Tagging(user:u2,tag:t,taggable:item2))
  32. }
  33. item2.save(flush:true)
  34. }
  35.  
  36. //setup()
  37.  
  38. t = Tag.findByName('tag1')
  39. itemsForUserAndTag = Taggable.withCriteria {
  40. and {
  41. eq('user', u2)
  42. tags {
  43. eq('tag', t)
  44. }
  45. }
  46. }
  47.  
  48. itemsForTag = Taggable.withCriteria {
  49. tags {
  50. eq('tag', t)
  51. }
  52. }
  53.  
  54. println "Items for user and tag: $itemsForUserAndTag.name"
  55. println "Items for tag: $itemsForTag.name"

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: dima767 on January 14, 2008

aszazx qasdlaks as';klas ascxla[scp;l'as;cl

You need to login to post a comment.