Search code examples
ruby-on-railsrating

Help: Adding rating to existing posts model in Rails


I've a simple posts model with title:string and rating:integer and I want to add the ability to rate the posts. So far I have

#Post controller   
def increase
 @post = Post.find(params[:id])
 @post.increment! :rating
 flash[:notice] = "Thanks for your rating."
 redirect_to @post
end

#Post show
<%= link_to "Rating", increase_post_path %>

#Routes
map.resources :posts, :member => { :increase => :put }

When I click on rating, I get unknown action. I'm able to increase the rating when I add @post.increment! :rating to update, but not when I create my own method. Any suggetions?


Solution

  • Here's my solution, if anyone is interested. Thanks for your help guys.

    #Views
    <%= link_to post.rating, increase_post_path(post) %>
    
    #Controller
    def increase
      @post = Post.find(params[:id]).increment!(:rating)
      flash[:notice] = "Thanks for rating"
      redirect_to posts_url
    end
    
    #Routes
    map.resources :posts, :member => { :increase => :put }
    

    This works if you want something just for you, something that won't be abused. Obviously adding rating to your websites where others can vote up unlimited times is just asking for trouble.

    I suggest using Votefu, does ratings and even has user karma. The author was nice enough to make an example app.