views:

85

answers:

3

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?

+1  A: 

You need to add the action to your routes.rb file. See this excellent guide for details.

JRL
+4  A: 

If you have a standard routes saying

map.resources :posts

you should replace it with:

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

And this will create the route "increase_post_path" with method "put" for your app.

fjuan
That's what I doing wrong, thanks.
Senthil
A: 

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.

Senthil