2016-04-11 148 views
2

我有一個名爲Items的組件,該組件稱爲ItemsContainer父項。當單擊Items中的按鈕時,將調用Ajax函數來刪除該Item。Ajax刪除請求ReactJS和Ruby on Rails

此刻,我收到了500條錯誤消息,我不知道爲什麼。

項目組件

class Item extends React.Component{ 

constructor(props) { 
    super() 

    this.state = { 
     name: '', 
     price: 0, 
     code: '', 
     id: '' 
    } 
} 

componentWillMount() { 
    this.setState({ 
     name: this.props.data.name, 
     price: this.props.data.price, 
     code: this.props.data.code, 
     id: this.props.data.id 
    }) 
} 

deleteItem() { 
    let finalUrl = '/items/' + this.state.id; 
    $.ajax({ 
     type: "DELETE", 
     url: finalUrl, /* THIS URL IS CALLING CORRECTLY ie. /items/8 */ 
     dataType: "json", 
     success: function(response) { 
      console.log("successfully deleted"); 
     }, 
     error: function() { 
      console.log("error"); 
     } 
    }) 
} 


render(){ 
    let itemName = this.props.data.name 
    let itemCode = this.props.data.code 
    let itemQuantity = 1 
    let itemPrice = (this.props.data.price * itemQuantity).toFixed(2) 
    const itemId = this.props.data.id 

    return(
     <tr> 
      <td>{itemName}</td> 
      <td>{itemCode}</td> 
      <td>{itemQuantity}</td> 
      <td><button className="btn btn-warning" onClick={this.deleteItem.bind(this)}>Remove</button></td> 
      <td>£{itemPrice}</td> 
     </tr> 
    ) 
} 

}

的Rails項目控制器

class ItemsController < ApplicationController 

def create 
    @item = Item.new(item_params) 
    if @item.save 
     render partial: 'items/item', locals: {item: @item} 
    else 
     render json: @item.errors.to_json 
    end 
end 

def destroy 
    if @item.destroy 
     render partial: 'items/item', locals: {item: @item} 
    else 
     render json: @item.errors.to_json 
    end 
end 

private 

def item_params 
    params.require(:item).permit(
     :name, 
     :price, 
     :code, 
     :id 
    ) 
end 

創建一個新的項目正在按預計,但我不知道爲什麼我收到我的刪除行動500錯誤。任何幫助將非常感激。

+1

請檢查您的銷燬方法在鐵路部分。我認爲它缺乏@item?如果我是對的? – Amit

+1

啊,是的,謝謝你的工作。我已經使用@item = Item.find(params [:id]),它現在運行良好:) –

+0

不確定,但因爲沒有經驗將軌道:) – Amit

回答

2

請檢查您的鐵路控制器中的銷燬方法。 @item沒有定義,因此500內部服務器錯誤:)