【问题标题】:how to delete a record in rails API and vue Js如何删除rails API和vue Js中的记录
【发布时间】:2019-02-19 01:06:57
【问题描述】:

我正在尝试使用 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"

我需要帮助

【问题讨论】:

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


    【解决方案1】:

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

    替换:

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

    与:

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

    【讨论】:

    • 我将 customer.id 更改为 id 。但是代码不起作用,我使用rails作为后端所以我在对象客户中只有customer.id。不要只有一个 id 键
    • 根据您的问题,您在 JS removecustomer 函数中有错误:customer undefined 并替换我建议的代码应该可以解决此问题。如果您遇到任何其他困难,您可以使用您遇到的适当错误更新问题,以便我可以更好地理解并为您提供帮助。
    • 谢谢,我必须配置 cors 以允许删除请求。
    • @pkimtani 有没有办法根据id 以外的内容进行删除,例如基于name? (问here
    猜你喜欢
    • 1970-01-01
    • 2015-06-01
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    相关资源
    最近更新 更多