alt*_*alt 3 ruby mysql ajax ruby-on-rails
所以我posts在Rails应用程序中生成了一个脚手架,我在帖子模型中添加了一个upvote和downvote列.我在视图文件上添加了一个"upvote"按钮,当你点击upvote按钮时我需要进行AJAX调用并查询数据库,但是upvote按钮没有<form>附加真正的Rails .如何进行此AJAX调用并将upvote添加到数据库以获取upvoted帖子?
当我进行这个AJAX调用时:
$('.up,.down').click(function(){
$.ajax({
type: 'POST',
url: '/posts',
dataType: 'JSON',
data: {
post: {
upvote: 1
}
},
success: function(){
alert('success')
}
});
});
Run Code Online (Sandbox Code Playgroud)
它返回500错误.我在哪里?
您可以:remote => true在link_to助手上使用该属性,例如:
<%= link_to post_upvote_path(post), :remote => true, :method => "put" %>
<%= link_to post_downvote_path(post), :remote => true, :method => "put" %>
Run Code Online (Sandbox Code Playgroud)
然后在config/routes.rb:
resources :posts do
put "upvote", :to => "posts#upvote", as: :upvote
put "downvote", :to => "posts#downvote", as: :downvote
end
Run Code Online (Sandbox Code Playgroud)
然后像你可能已经在你的帖子控制器中处理投票,并params[:id]在操作中获取帖子ID
更新
要查看已创建的upvote和downvote路线,请转至终端并键入
rake routes | grep vote
Run Code Online (Sandbox Code Playgroud)
这将为您提供名称中包含"投票"的所有路线的列表.或者只需输入rake routes即可获得所有这些列表.第一列是命名路由,只需在其末尾附加'_path'即可在您的应用中使用它 - post_upvote_path如上所示将被视为
post_upvote PUT /posts/:id/upvote(.:format) posts#upvote
Run Code Online (Sandbox Code Playgroud)
在你的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
Run Code Online (Sandbox Code Playgroud)