How do I add a '+1' link in a Rails 3 app that when clicked increases the Upvotes value by 1?
I'm new to programming.
I generated an Ideas scaffold. The model has fields: Description (string), Upvotes (integer), Downvotes (integer).
All the normal actions in the ideas_controller.rb work - Index, Show, New, Edit, Create, Update, Destroy.
Instead of telling you the ways I've tried to do the following, I'll just ask:
How do I add a '+1' link next to the 'Show', 'Edit', 'Destroy' links that when clicked increases the Upvotes value by 1 for that idea?
Thanks in advance.
EDIT (With "Skydreamer's" help, I figured it out!)
I adjust the routes.rb to:
resources :ideas do
member do
get 'upvote'
end
end
I add the following to the ideas index.html.erb:
<td><%= link_to '+1', upvote_idea_path(idea) %&g开发者_如何学Got;</td>
Note: if you don't include the (idea), you'll get an error like this:
No route matches {:action=>"upvote", :controller=>"ideas"}
I add the following to the ideas_controller.rb:
def upvote
@idea = Idea.find (params[:id])
@idea.upvotes = @idea.upvotes + 1
@idea.save
redirect_to(ideas_url)
end
In the next lines, I'll say upvote but that works the same for downvote.
First, create a member route upvote
, then you can link from your show view to the new action using upvote_idea_path
.
Second, create an action upvote
in the controller which increases the vote count by 1 and you're done. That's all.
You can achieve this functionality with the thumbs_up gem. It is also Rails 3 compatible.
精彩评论