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

时间:2015-07-07 05:25:54

标签: jquery ruby-on-rails ajax

我有一个模型让我们说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');
                  }
              });
    });
});

1 个答案:

答案 0 :(得分:1)

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

假设在名为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
     })
    });
});

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