0

I have a Book class and need to implement a yes/no voting functionality. My domain classes look like this:

class Book {
   String title
   static hasMany = [votes: Vote]
}

class User {
  String name
  static hasMany = [votes: Vote]
}

class Vote {
  boolean yesVote
  static belongsTo = [user: User, book: Book]
}

What is the best way to implement a voting for the book class. I need the following informations:

  • What is the average yesVote for a book over all votes (either yes or no)?
  • How to check if a specific user has done a vote?

What is the best way to implement the computation of the average yesVote such that the performance does not drop?

Michael
  • 32,527
  • 49
  • 210
  • 370

2 Answers2

1

I would add a totalVotes to Book. Incremenent that for each yes vote. Then a simple count() of votes for a book along with the totalVotes value gives you what you need.

Update: Answering your comment questions:

  1. def yesVotes = Vote.findAllByBookAndYesVote(bookInstance, Boolean.TRUE)

  2. def votes = Vote.findAllByBook(bookInstance)

  3. def userVote = Vote.findByUserAndBook(userInstance, bookInstance)

Gregg
  • 34,973
  • 19
  • 109
  • 214
  • In your way you cannot see if a specific user has voted and if he voted yes or no. Any other ideas? – Michael Nov 06 '12 at 00:15
  • Well, those are 2 different things. You had 2 bullet points and then asked one question. I assumed you knew you could simply do a Vote.findAllByUserAndYesVote(user, Boolean.TRUE) along with other variations of the same query. If you're asking for something more complex, you should update your question. – Gregg Nov 06 '12 at 02:56
  • can you provide some code for your example. I need to answer the following questions: 1. What is the number of yesVotes for a specific book? 2. What is the number of total votes for this book? 3. Has a current user voted for a specific book and what was his voting result? What is the list of books a user voted yes for? By the way would you do the voting class in the same way as I did? Thanks for your help. – Michael Nov 06 '12 at 10:35
  • I have user instance. How can I get all books from user.books which where rated with yesVote by user? – Michael Nov 10 '12 at 12:39
  • You really need to start reading some Grails documentation. def yesVotes = Vote.findAllByUserAndYesVote(userInstance, Boolean.TRUE) and then you could do def books = yesVotes.collect { it.book } – Gregg Nov 10 '12 at 16:37
0

Well, my opinion is :

  1. First way - One Service with a method addVote(user, book, true/false), and two others methods addPositiveVote(user, book) and addNegativeVote(user, book);

  2. Second way - the business rules shoud be in the domains, put a method addVote in the book addVote(user, true/false).

This a simple process, the performance dont drop, my considerations only contemplate the modeling.

Sorry for my bad english.