简体   繁体   中英

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

I have a model let's say Student and I want to edit a row in the table name students through Ajax after clicking a button, what is the correct way to do this? Also, please note I want to edit value inside one column followers

Here is the js code:

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

Create a new method and define it into the route file:

Suppose, in the students_controller.rb file named update_followers

Then in the students_controller.rb file,

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

In your script :

$(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
     })
    });
});

As I don't know about your model attributes thus you have to modify the code according to your want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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