weixin_33726318 2016-09-14 04:12 采纳率: 0%
浏览 33

结合使用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?

  • 写回答

2条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 房号如何排序,sql或算法
      • ¥15 macOS使用IDEA 2022.2.4打包JDK6项目报错
      • ¥20 OpenCV-Python简单轮廓寻找
      • ¥20 使用matlab进行含参数的最优化求解及数值模拟
      • ¥20 MATLAB找出一维变量中的局部极大值和局部极小值,并进行运算
      • ¥15 有Chang求三维杆单元几何非线性分析matlab代码
      • ¥50 使用unity easyar录屏功能。录屏视频整体色调很暗
      • ¥50 pyinstaller 打包问题
      • ¥15 无法使用cnssc调取网页数据
      • ¥15 Pycharm安装en_core_web_sm失败出现Could not find a version that satisfies the requirement spacy报错