Вопрос

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?

Это было полезно?

Решение

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)

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top