Rails 3 rateable model - How to create ajax rating?

前端 未结 2 1692
北恋
北恋 2020-12-17 06:46

How do I create some simple ajax rating like there is on this page http://watir.com/documentation/ ? Every visitor should be able to rate, I dont need to set permissions. I

2条回答
  •  佛祖请我去吃肉
    2020-12-17 07:40

    What I did recently to add a simple rating mechanism to an existing project was the following:

    I added two fields to an existing table (which contained the items to be rated). Those were:

    rating_score => The current score
    ratings => The number of ratings which led to the score
    

    For example, if five users would've voted "5" for the current item, rating_score would be 25, and ratings would be 5. The current rating would be computed as rating_score / ratings.

    Then I added a new method to the controller of the items to be rated, called "rate", which looked something like:

    def rate
        @item = Item.find(params[:id])
        @container = "item"+@item.id.to_s
    
        @item.rating_score += params[:rating].to_i
        @item.ratings += 1
        @item.save
    
        respond_to do |format|
            format.js
        end
    end
    

    My view for that method, called rate.js.erb, would look something like

    $('#<%= @container %>').html('<%= escape_javascript(render(partial: 'rating', locals: { item: @item })) %>');
    

    This code works only if you've got jQuery installed, but it should be easily translatable to Prototype or whatever JS framework you may be using.

    And the partial for the rating, called _rating.html.erb, was something like:

    <%= form_tag url_for(controller: 'items',  action: 'rate', id: item.id), remote: true %>
        <%= rating_stars(item.rating_score, item.ratings) %>
        <%= item.ratings %> Votes
    
    

    In this partial, the rating_stars() helper method generated some kind of star-like representation for the rating, but you can do that however you like.

    By setting "remote: true" in the form_tag helper, your Rails installation should automatically transmit the request via the installed Javascript framework. This magic is part of the whole unobtrusive javascript thing going on in Rails lately, which is actually pretty cool.

    Hope this gives you an idea of how to realize a very simple rating system with no IP lock feature whatsoever in Rails.

提交回复
热议问题