我最近怎么一个简单的评级机制添加到现有的项目是以下几点:
我加了两个字段到一个现有的表(包含的项目进行评估)。这些都是:
rating_score => The current score
ratings => The number of ratings which led to the score
例如,如果有五个用户就已经评选为“5”当前项目,rating_score
为25,和收视率是5,额定电流将被计算为rating_score/ratings
。
然后我加入到项目的控制器的新方法来连续被评为,被称为“率”,它看上去是这样的:
def rate
@item = Item.find(params[:id])
@container = "item"[email protected]_s
@item.rating_score += params[:rating].to_i
@item.ratings += 1
@item.save
respond_to do |format|
format.js
end
end
我为这个方法看来,所谓的rate.js.erb
,看起来是这样的
$('#<%= @container %>').html('<%= escape_javascript(render(partial: 'rating', locals: { item: @item })) %>');
此代码仅当您已安装了jQuery的,但它应该是容易翻译到原型,或者你可以使用任何JS框架。
而且partial的评级,称为_rating.html.erb
,是这样的:
<%= form_tag url_for(controller: 'items', action: 'rate', id: item.id), remote: true %>
<%= rating_stars(item.rating_score, item.ratings) %>
<%= item.ratings %> Votes
</form>
在这部分中,rating_stars()
helper方法产生某种对评级明星般的表现,但你可以做到这一点不过你喜欢。
通过在form_tag helper中设置“remote:true”,您的Rails安装应该通过安装的Javascript框架自动发送请求。这个魔术是最近在Rails上完成的整个unobtrusive javascript的一部分,这实际上很酷。
希望这可以让你了解如何实现一个非常简单的评分系统而不需要任何IP锁定功能在Rails中。
https://github.com/edgarjs/ajaxful-rating – Zabba 2011-02-17 19:57:20
它dosent与轨道3工作 – 2011-02-17 20:00:51