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 u开发者_开发问答nknown 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?
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.
You need to add the action to your routes.rb
file. See this excellent guide for details.
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.
精彩评论