繁体   English   中英

Rails 4-Ajax表单添加新记录,而不是编辑当前记录

[英]Rails 4 - Ajax form adding a new record instead of editing the current record

我有一个模型,假设Student并且我想在单击按钮后通过Ajax在表名“ students编辑一行,这样做的正确方法是什么? 另外,请注意,我要编辑一列followers

这是js代码:

    $(document).ready(function(){
    $('.clap').click(function(){
        var dataString = "student[followers]=5";
         $.ajax({
                type: "POST",
                url: "/students/",
                data: dataString,
                success: function() {
                  window.alert('success');
                  }
              });
    });
});

创建一个新方法并将其定义到路由文件中:

假设在students_controller.rb文件中,名为update_followers

然后在students_controller.rb文件中,

def update_followers
  puts params[:followers] // this parameter will come from the ajax 
  redirect_to students_path
end

在您的脚本中

$(document).ready(function(){
    $('.clap').click(function(){
        $.ajax({
         type: 'POST',
         url: '<%= student_update_followers_path(params[:id]) %>', // in your project directory use console command `rake routes | grep update_followers` to find the method url 
         data: {followers: 5} // define the parameters and values you want to pass to the method
     })
    });
});

由于我不知道您的模型属性,因此您必须根据需要修改代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM