如何在 play 框架中实现投票系统?

How to implement a voting system in the play framework?

我正在尝试为诸如 SO 或 reddit 之类的问题/答案实施投票系统。 到目前为止,我已经嘲笑了一些问题和答案。有一个带有箭头的脚本用于 upvote / downvote 更改箭头的颜色并增加箭头旁边的数字以指示投票数。

但现在我卡住了。

模拟答案/问题需要由scala-template生成,不是我手动输入的。我不知道该怎么做。

这是给箭头上色并计票的脚本: (不得不说目前只有第一个箭头起作用,这可能是因为ID应该是唯一的,所以第二个箭头会被忽略?)

<script>
    $(document).ready(function() {
        $('#icon').click(function() {
            var $this = $(this);
            $this.css("color","orange");
            var num = $('#num');
            var currentNumber = num.text().length ? parseInt(num.text()) : 0;
            num.text(currentNumber + 1);
        });
    });
</script> 

这是一些带有箭头的答案列表条目的示例和我也手动输入的投票号码:

<li class="list-group-item" > <span id="icon" class="glyphicon glyphicon-arrow-up" aria-hidden="true"></span><span id="num"></span> 7 <span class="glyphicon glyphicon-arrow-down" aria-hidden="true"></span> Die Schleife springt durch <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> <span class="glyphicon glyphicon-remove" aria-hidden="true"></span></li>
<li class="list-group-item" > <span id="icon" class="glyphicon glyphicon-arrow-up" aria-hidden="true"></span><span id="num"></span> 1 <span class="glyphicon glyphicon-arrow-down" aria-hidden="true"></span> Das Programm hängt sich auf <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> <span class="glyphicon glyphicon-remove" aria-hidden="true"></span></li>

这是目前的照片。

我该如何从这里开始?我是 play 框架的新手,它是 scala 模板,所以也许我可以以某种方式让框架生成一个通用的箭头/投票组合,我可以稍后处理而不是手动放入这些行? 我是否必须以某种方式将选票保存在真实数据库中? 我如何进一步处理选票,即如何将它们放入变量中?

Whosebug 上还有其他几个与我类似的问题,但几乎 none 中使用的是 play 框架。

[编辑]: 这是一个 JSfiddle,只需单击最左边的箭头即可。

假设您有一个 class Question,只有一个字段 'text'

class Question {
    long id;
    String text;
}

还有一个 class Answer 有一个字段 'text'

class Answer {
    String text;
}

现在在你的控制器中(也许 Application.java)首先你得到问题和相应的答案,然后你将它们提供给你的视图:

public static Result showQuestion() {
    Question q = Question.find.byId(1);
    List<Answer> possibleAnswers = Answer.findByQuestion(q);
    return ok(showquestion.render(q, possibleAnswers);
}

现在在你看来你有这个:

@(q: Question, answers: List[Answer])

<h3>@q.text</h3>

<ul>
@for(answer <- answers){
    <li>@answer.text</li>
}
</ul>

当然,答案的标记可以很复杂(包括投票、箭头、图标等)。