如何在Rails API和Vue Js中删除记录

时间:2019-02-19 01:06:58

标签: ruby-on-rails vuejs2 rails-api

我正在尝试使用axios库删除ActiveRecord表单Rails API和Vue js。我可以毫无问题地获取和添加记录。我遇到的问题是删除记录

这是我的代码

rails API .....

# DELETE v1/customers/1
 def destroy
  @customer = Customer.find(params[:id])
  @customer.destroy
end

Vue Js ........

<tr v-for="customer in customers" :key="customer.id">
  <td>{{customer.first_name}}</td>
   <td>{{customer.last_name}}</td>
    <td>{{customer.email}}</td>
     <td>{{customer.id}}</td>
     <td><button @click="removecustomer(customer.id)"
     type="button" class="btn btn-outline-danger btn-sm">Delete</button></td>

 export default {
  name: 'customers',
    data (){
        return{
            customers:[]
        }
    },
    created (){
        this.getallcustomers()
    },
     methods: {
       getallcustomers () {
             let uri = 'http://localhost:3000/v1/customers';
            this.axios.get(uri).then((response) => {
               this.customers = response.data;
               console.log(this.customers);

            });
       },
        removecustomer(id){
             let uri = `http://localhost:3000/v1/customers/${customer.id}`;
             this.axios.delete(uri).then((res) => {
               this.customers = this.customers.filter(customer => customer.id !== id);



            });
        }
    }

}

所以我的removecustomer方法会产生错误customer is not defined"

我需要帮助

1 个答案:

答案 0 :(得分:3)

您仅将客户ID作为参数(id)传递给removecustomer函数,而不是整个customer对象,因此,您将得到未定义的错误。

替换:

let uri = `http://localhost:3000/v1/customers/${customer.id}`

使用:

let uri = `http://localhost:3000/v1/customers/` + id