So I have a posts scaffold generated in a Rails app and I’ve added an upvote and downvote column to the post model. I added an “upvote” button on the view file and I need to make an AJAX call and query the database when you hit the upvote button, but the upvote button has no real Rails <form> attached to it. How can I make this AJAX call and add the upvote to the database for the upvoted post?
When I make this AJAX call:
$('.up,.down').click(function(){
$.ajax({
type: 'POST',
url: '/posts',
dataType: 'JSON',
data: {
post: {
upvote: 1
}
},
success: function(){
alert('success')
}
});
});
It returns a 500 error. Where do I go form here?
You could use the
:remote => trueattribute on thelink_tohelperfor example:
then in
config/routes.rb:then handle the voting in your posts controller, like you probably already are and grab the post id with
params[:id]in the actionHere is an intro to rails flavored unobtrusive javascript
Update
To see the upvote and downvote routes that were created, go to the terminal and type
this will give you a list of all of your routes that have “vote” in the name. Or just type
rake routesto get a list of all of them. The first column is the named route, just append ‘_path’ to the end of it to use it in your app – likepost_upvote_pathabove would be seen asAnd in you PostsController you would want these actions: