【问题标题】:Ajax Delete request ReactJS and Ruby on RailsAjax 删除请求 ReactJS 和 Ruby on Rails
【发布时间】:2016-04-11 10:01:14
【问题描述】:

我有一个名为 Items 的组件,它位于名为 ItemsContainer 的父级中。单击 Items 中的按钮时,将调用 Ajax 函数来删除该 Item。

但目前我收到 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 错误。任何帮助将不胜感激。

【问题讨论】:

  • 请检查您在铁路部分的销毁方法。我认为它缺少@item?如果我是对的?
  • 啊,是的,谢谢。我用过@item = Item.find(params[:id]) 现在运行良好:)
  • 不确定,因为没有经验会出轨:)

标签: javascript jquery ruby-on-rails ajax reactjs


【解决方案1】:

请检查您在铁路控制器中的销毁方法。 @item 没有定义,因此 500 内部服务器错误:)

【讨论】:

    猜你喜欢
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 2012-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-30
    相关资源
    最近更新 更多