ActiveRecord :: RecordNotFound with ajax destroy

时间:2015-11-02 00:00:00

标签: ruby-on-rails ruby ajax

我目前正在使用带有ajax的rails应用程序,但由于遇到ActiveRecord::RecordNotFound in ItemsController#destroy错误,destroy函数无法正常工作。

有关其他信息,我可以删除该项目,但ajax部分无法正常工作,只有刷新页面时该项目才会消失。

我似乎无法确定问题的主要来源,我目前需要一些帮助。

提前致谢!

items_controller.rb

    class ItemsController < ApplicationController

  def create
    @item = current_user.items.build(item_params)
    if @item.save
        flash[:notice] = "Item was saved"
        redirect_to user_path(current_user)
    else
        flash[:error] = "There was an error saving the item. Please try again"
        render :new

    end
  end

  def destroy
    @items = Item.find(params[:id])

    if @items.destroy
      flash[:notice] = "Item was removed"
    else
      flash[:error] = "Item couldn't be deleted.try again!"
    end
  end

     respond_to do |format|
     format.html
     format.js
   end

  def new
    @item = Item.new
  end

  private

  def item_params
    params.require(:item).permit(:name)
  end

end

users_controller.rb

class UsersController < ApplicationController
before_action :authenticate_user!, except: [:show]

    def new
        @user = User.new
    end


    def show
   @user = params[:id].nil? ? current_user : User.find(params[:id])
    @items = @user.items
    end

   def update
    if current_user.update_attributes(user_params)
      flash[:notice] = "User information updated"
      redirect_to edit_user_registration_path
    else
      flash[:error] = "Invalid user information"
      redirect_to edit_user_registration_path
        end
    end


   private

   def user_params
     params.require(:user).permit(:name)
   end
 end

_item.html.erb

 <p id="items-<%= item.id %>">
    <%= link_to "", [current_user, item], method: :delete,remote: true, class: 'glyphicon glyphicon-ok' %>
    <%= item.name %>
 </p>

destroy.js.erb

<% if @items.destroyed? %>
   $('#items' +<%= @items.id %>).hide();
 <% else %>
   $('#items' +<%= @items.id %>).prepend("<div class='alert alert-danger'><%= flash[:error] %></div>");
 <% end %>

的routes.rb

Rails.application.routes.draw do


  devise_for :users
  resources :users, only: [:update, :show, :new, :index]

  resources :users do
    resources :items, only: [:create, :new, :destroy]
  end


   authenticated :user do
 root to: "users#show", as: :authenticated_root, via: :get
end


unauthenticated do
  root 'welcome#index'
end

end

2 个答案:

答案 0 :(得分:0)

natural('05')
True

natural('asasassaas')
False

natural('243,432,355')
False

在重定向/渲染任何内容之前,您似乎正在结束#destroy方法。

答案 1 :(得分:0)

我认为你必须修复你的破坏方法:

def destroy
  @items = Item.find(params[:id])

  if @items.destroy
    flash[:notice] = "Item was removed"
  else
    flash[:error] = "Item couldn't be deleted.try again!"
  end
  respond_to do |format|
    format.html
    format.js
  end
end

我希望这对你有所帮助。