javascript - rails : Using JQuery for post request instead of link_to

标签 javascript jquery ruby-on-rails ajax

现在,我的 Rails 应用程序中有一个“投票”模型。页面上的每个帖子都有一个点赞按钮,目前写为:

<%= link_to "✓", votes_path(:vote => {:post_id => post.id, :up => false}), :method => :post %>

其中 post_id 是投票所链接的帖子,而 up 是一个 bool 值,表示投票是正确的。我正在尝试使用 JQuery 而不是 link_to,这样页面就不会在每次有人投票时重新加载。但是,我不明白 AJAX post 请求与数据库模型的接口(interface)是什么样的。

编辑:投票 Controller :

def create
    respond_to do |format|
        format.html
        format.js { flash[:notice] = "Vote created"} # and render your <action>.js file}
    end
    @vote = Vote.where(:post_id => params[:vote][:post_id], :user_id => current_user.id).first
    if @vote
        @vote.up = params[:vote][:up]
        @vote.save
    else
        @vote = current_user.votes.create(vote_params)
    end 
    redirect_to :back
end

最佳答案

使用remote: true ajax 调用选项。

<%= link_to "✓", votes_path(:vote => {:post_id => post.id, :up => false}, :format => :js), :method => :post, remote: true %>

它将生成一个对您的 Controller 的 ajax 调用。然后你可以相应地操纵你的 Action 。

respond_to do |format|
 format.html
 format.js { flash[:notice] = "Vote created"} # and render your <action>.js file
end

更新

def create
    @vote = Vote.where(:post_id => params[:vote][:post_id], :user_id => current_user.id).first
    if @vote
        @vote.up = params[:vote][:up]
        @vote.save
    else
        @vote = current_user.votes.create(vote_params)
    end 
    respond_to do |format|
        format.html
        format.js { flash[:notice] = "Vote created"} # and render your <action>.js file}
    end
end

应该可以,请告诉我

还要检查这个..

您的app/assets/javascripts/application.js应该包含。

//= require jquery 
//= require jquery_ujs

你的 erb 应该包含

<%= javascript_include_tag "jquery", "jquery_ujs" %>

关于javascript - rails : Using JQuery for post request instead of link_to,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29937550/

相关文章:

javascript - Google+ API 不返回 access_token Javascript

javascript - 如何测试javascript cookie是否已过期?

ruby-on-rails - Ruby on Rails 总是指向本地的 redis 服务器

javascript - NodeJS Await 优先级 - 一个 Await 以错误的顺序在另一个 Await 之前运行(Express、SQLite3 db.all 和 db.run)

c# - 为什么对 C# Web 方法的 jQuery ajax 调用不起作用

javascript - 使用来自输入的链接填充 href

javascript - 如何将自定义 td 附加到从二维数组生成的表中?

ruby-on-rails - 在 Rails 模型/表中验证 presense 与 null false

ruby-on-rails - 不断获取Authentication+failed.+API+credentials+are+incorrect

javascript - 如何在 Meteor 中创建选择控件