微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

mysql – 在没有表单的情况下在Rails中发出AJAX请求

所以我在Rails应用程序中生成一个帖子脚手架,我在帖子模型中添加一个upVote和downVote列.我在视图文件添加一个“upVote”按钮,当你点击upVote按钮时我需要进行一次AJAX调用查询数据库,但是upVote按钮没有真正的Rails< form>附在它上面.如何进行此AJAX调用并将upVote添加数据库获取upVoted帖子?

当我进行这个AJAX调用时:

$('.up,.down').click(function(){
    $.ajax({
      type: 'POST',
      url: '/posts',
      dataType: 'JSON',
      data: {
        post: {
          upVote: 1
        }
      },
      success: function(){
        alert('success')
      }
    });
  });

它返回500错误.我在哪里?

解决方法:

你可以使用:remote => link_to帮助器上的true属性
例如:

<%= link_to post_upVote_path(post), :remote => true, :method => "put" %>
<%= link_to post_downVote_path(post), :remote => true, :method => "put" %>

然后在config / routes.rb中:

resources :posts do
  put "upVote", :to => "posts#upVote", as: :upVote
  put "downVote", :to => "posts#downVote", as: :downVote
end

然后处理你的帖子控制器中的投票,就像你可能已经是,并在动作中使用params [:id]获取帖子ID

Here is an intro to rails flavored unobtrusive javascript

更新
要查看已创建的upVote和downVote路线,请转至终端并键入

rake routes | grep Vote

这将为您提供名称中包含“投票”的所有路线的列表.或者只需输入rake路线即可获得所有这些路线的列表.第一列是命名路由,只需在其末尾附加’_path’即可在您的应用中使用它 – 如上面的post_upVote_path将被视为

post_upVote  PUT  /posts/:id/upVote(.:format) posts#upVote

在你的PostsController中你会想要这些动作:

class PostsController < ApplicationController
  ###
  # index, show... other RESTful actions here
  ###


  def upVote
    @post = Post.find params[:id]
    # code for however you are voting up the post here
  end

  def downVote
    @post = Post.find params[:id]
    # code for however you are voting down the post here
  end
end

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐