结合使用Ajax和Ruby

I am trying to get back into Ruby, and creating a simple vote up and down system (like reddit).

I can get the votes to work, but the page reloads each time. I am trying to implement an ajax call to change the values dynamically, but the only guides I can find are for Rails. I am just using Ruby with a Sinatra server.

the html.erb

<form action="/votes" method="post">
    <input type="hidden" name="post_id" value="<%= post.id %>">
    <button id="thumb-up"><img src="/images/thumbs-up.gif" /></button>
  </form>
    <p> <%= post.votes.count %> </p>
  <form action="/votes" method="post">
    <input type="hidden" name="_method" value="delete">
    <input type="hidden" name="post_id" value="<%= post.id %>">
    <button id="thumb-down"><img src="/images/thumbs-down.gif" /></button>
  </form>

jquery

$('#thumb-up').on('click', function(e) {
  e.preventDefault();

$.ajax({
    url: '/votes',
    method: 'post',
    success: function() {
      console.log('vote up');
      $(this).html("<%= post.votes.count %>");
    }
  })
});

and the model

class Vote < ActiveRecord::Base
  belongs_to :user
  belongs_to :post

  validates :post, uniqueness: { scope: :user }
  validates :user, uniqueness: { scope: :post }

end

The routes (sorry, added later)

post '/votes' do
  if logged_in?
    vote = Vote.new
    vote.user_id = current_user.id
    vote.post_id = params[:post_id]
    vote.save
    redirect to '/'
  else
    redirect to '/session/new'
  end
end

delete '/votes' do
  if logged_in?
    votes = Vote.where(user_id: current_user.id, post_id: params[:post_id])

    votes.each do |vote|
      vote.delete
    end
    redirect to '/'
  else
    redirect to '/session/new'
  end
end

Now I'm guessing this is a super simple thing, and I know that remote: true has something to do with it.

At the moment I get a 500 error with the thumb-up button, but not with the thumb-down, which has url: 'delete' instead of post.

Can I accomplish this without having a form for each button?

I had worked on same thing, its easy if u ajax call like this

<%= link_to image_tag(likepic), like_post_path(post,status: true),  class: 'vote', method: :put, remote: true %> 

like_user_path goes to "like" method in post controller and posts status:true means "liked"

hope it works, because it worked for me

and the model is

class Like < ActiveRecord::Base
  belongs_to :user
  belongs_to :post
end

I think the error is here:

validates :post, uniqueness: { scope: :user }

and here

$.ajax({
    url: '/votes',
    method: 'post',
    success: function() {
      console.log('vote up');
      $(this).html("<%= post.votes.count %>");
    }
  })

Your vote requires a post id, but you don't send one in your ajax request.