0

I have different classes in my Grails application that a user should create comments for. E.g., Post, Book, Article

Setting

static hasMany = [comments: Comment]

to each class seems to be a bad solution. What is the best way to make them commentable? How should a generic Comment class look like?

Michael
  • 32,527
  • 49
  • 210
  • 370
  • Why do you think its a bad solution ? – Nix May 06 '13 at 18:50
  • It seems to be not so elegant. How do I create to Comment class? – Michael May 06 '13 at 18:53
  • 1
    There is actually a [Commentable Plugin](http://grails.org/plugin/commentable) that works very well. – Kelly May 06 '13 at 19:03
  • I used a custom comment implementation for mine. If all you are doing is linking a "comment" to something, your implementation is not flawed, or "ugly." – Nix May 06 '13 at 19:27

4 Answers4

0

The simplest is to define a commentable interface in src/groovy and have your classes inherit this interface. This is just normal java coding but enables you to centralize all your comment related code, hopefully around a grails service. If you want to get fancy you can use an annotation for this.

Once you have done that, you can move this code out into a plugin so you can use it in different projects.

Tomas Lin
  • 3,532
  • 1
  • 22
  • 19
  • 5
    Sure, and you could call the plugin "commentable" too ;) http://grails.org/plugin/commentable – Burt Beckwith May 06 '13 at 19:35
  • 1
    yes, but the more common scenario I've seen is people using facebook or disqus comments instead of building it all in-house. In which case comments are really just a boolean. This solution fits both use cases. – Tomas Lin May 06 '13 at 21:35
0

Why is that a bad solution? Looks exactly right to me. Your domain class does indeed have many comments, right?

Georgemc
  • 369
  • 1
  • 5
0

You can create also abstract base class Commentable, then other domains can extend Commentable. Now you can create Comment class with belongsTo commentable. You can also implement getComments in Commentable class by simple Commentable.findAllBy(this). In my opinion is also good idea to avoid "hasMany" relations.

Grzegorz Gajos
  • 2,253
  • 19
  • 26
0

You can use Inheritance here.

Create Base class which will have this setting

 static hasMany = [comments: Comment]

& let all other classes i.e. Post, Book, Article, Inherit it.

swapy
  • 290
  • 2
  • 9