簡體   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