views:

437

answers:

2

My database consists of 3 tables (one for storing all items, one for the tags, and one for the relation between the two):

Table: Post Columns: PostID, Name, Desc

Table: Tag Columns: TagID, Name

Table: PostTag Columns: PostID, TagID

What is the best way to save a space separated string (e.g. "smart funny wonderful") into the 3 database tables shown above?

Ultimately I would also need to retrieve the tags and display it as a string again. Thanks!

+1  A: 

If you have a Tag Table, wouldn't you have a row for each Tag?

tag.id = 1; tag.name = 'smart'
tag.id = 2; tag.name = 'funny'
tag.id = 3; tag.name = 'wonderful'

In Groovy/Grails, you'd retrieve them as a list, possibly concatenating them into a space separated list for display.

Unless I'm really misunderstanding the question, Groovy/Grails/GORM will handle this with little or no code with the default scaffolding, no real coding required.

Ken Gentle
I agree, you're correct for retrieving and displaying the tags. I think he is stuck on how to take 3 words from 1 form field and insert 3 records in the tag table.
Ed.T
Yes, I think that's what I was trying to get at. But I wasn't able to articulate the problem initially. I'll edit the original question now.
Walter
Looks like 'Hates_' has an answer
Ken Gentle
+4  A: 

Roughly, something like this:

class Post {
    static hasMany [tags:Tag]
}

class Tag {
    static belongsTo = Post
    static hasMany [posts:Post]
}

class someService {

    def createPostWithTags(name, desc, tags) {  
     def post = new Post(name: name, desc: desc).save()
     tags.split(' ').each { tagName ->
      def tag = Tag.findByName(tag) ?: new Tag(name: tagName)
      post.addToTags(tag).save()
     }  
    }

}
Hates_
Thanks Hates_. This solution works well. I just had to make a small change: def tag = Tag.findByName(tag) ?: new Tag(name: tagName).save()
Walter