Params [:id]返回ActiveRecord :: RecordNotFound错误

时间:2016-04-12 03:43:15

标签: ruby-on-rails ruby activerecord

当我尝试通过它的ID检索对象时,我需要帮助弄清楚为什么我得到ActiveRecord :: RecordNotFound错误。以下是我的错误和代码。如果需要在此帖子中添加任何其他文件,请与我们联系。提前感谢您的帮助!

错误

ActiveRecord::RecordNotFound in WikisController#show

Couldn't find Wiki with 'id'=edit

def show
    @wiki = Wiki.find(params[:id]) #Highlighted line within error
    authorize @wiki
end

控制器

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

  def index
    @wikis = Wiki.visible_to(current_user)
    authorize @wikis
  end

  def new
    @wiki = Wiki.new
    authorize @wiki
  end

  def create
    @wiki = current_user.wikis.create(wiki_params)
    authorize @wiki

    if @wiki.save
      flash[:notice] = "Wiki was saved."
      redirect_to @wiki
    else
      flash.now[:alert] = "Error saving Wiki. Try again."
      render :new
    end
  end

  def show
    @wiki = Wiki.find(params[:id])
    authorize @wiki

    unless @wiki.private == nil
      flash[:alert] = "You must be signed in to view private topics."
      redirect_to new_session_path
    end
  end

  def edit
    @wiki = Wiki.find(params[:id])
    authorize @wiki
  end

  def update
    @wiki = Wiki.find(params[:id])
    authorize @wiki

    if @wiki.update_attributes(wiki_params)
      flash[:notice] = "Wiki was updated."
      redirect_to @wiki
    else
      flash.now[:alert] = "Error saving the Wiki. Try again."
      render :edit
    end
  end

  def destroy
    @wiki = Wiki.find(params[:id])
    authorize @wiki

    if @wiki.destroy
      flash[:notice] = "\"#{@wiki.title}\" was deleted successfully."
      redirect_to root_path
    else
      flash.now[:alert] = "Error deleting Wiki. Try again."
      render :show
    end
  end

  private

  def wiki_params
    params.require(:wiki).permit(:title, :body, :role)
  end
end

路线

Rails.application.routes.draw do

  resources :wikis
  resources :charges, only: [:new, :create]

  devise_for :users
  resources :users, only: [:update, :show] do
    post 'downgrade'
  end

  get 'welcome/index'
  get 'welcome/about'
  root 'welcome#index'
end

2 个答案:

答案 0 :(得分:2)

您似乎正在访问wikis/edit网址而不是wikis/:id/edit。确保在您的视图中正确生成了您的链接。

答案 1 :(得分:0)

请确保在您的视图中有类似的内容(如果使用erb):

<%= link_to edit_wiki_path(@wiki) %>

你也可以使用before_action

来缩短你的控制器
class WikisController < ApplicationController
  ...
  before action :set_wiki, only: [:show, :edit, :update, :destroy]

  ...

  private

  def set_wiki
    # Now this is being set in your show, edit, update, destroy method
    # Make sure to delete from the above mentioned methods
    @wiki = Wiki.find(params[:id])
  end