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条回答 默认 最新

  • csdnceshi62 2016-09-14 06:02
    关注

    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
    
    评论

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗