Ruby on Rails show.html.erb undefined方法`naam'代表nil:NilClass

时间:2014-08-05 20:02:37

标签: ruby-on-rails-4

我是Ruby on Rails的新手。我创建了一个用于学习目的的基本应用程序。

当创建记录时,我重定向以显示操作并获得错误:未定义的方法`naam'代表nil:NilClass。

我做错了什么?

佣金路线

     Prefix Verb   URI Pattern                  Controller#Action
welcome_index GET    /welcome/index(.:format)     welcome#index
     relaties GET    /relaties(.:format)          relaties#index
              POST   /relaties(.:format)          relaties#create
   new_relaty GET    /relaties/new(.:format)      relaties#new
  edit_relaty GET    /relaties/:id/edit(.:format) relaties#edit
       relaty GET    /relaties/:id(.:format)      relaties#show
              PATCH  /relaties/:id(.:format)      relaties#update
              PUT    /relaties/:id(.:format)      relaties#update
              DELETE /relaties/:id(.:format)      relaties#destroy
         root GET    /                            welcome#index

relaties_controller.rb

class RelatiesController < ApplicationController

def new
    @relatie = Relatie.new
end

def create
    @relatie = Relatie.new(relatie_params)
    @relatie.save
    redirect_to @relatie
end

    private
      def relatie_params
        params.require(:relatie).permit(:id, :naam, :straatnaam, :huisnummer, :postcode, :plaats, :omschrijving)    
      end   

    def show
        @relatie = Relatie.find(params[:id])
    end 
 end

的routes.rb

  Rails.application.routes.draw do
  get 'welcome/index'
  resources :relaties   
  root 'welcome#index'

show.html.erb

    <p>
  <strong>Naam:</strong>
  <%= @relatie.naam %>
</p>

<p>
  <strong>Straatnaam:</strong>
  <%= @relatie.straatnaam %>
</p>

<p>
  <strong>Huisnummer:</strong>
  <%= @relatie.huisnummer %>
</p>

<p>
  <strong>Postcode:</strong>
  <%= @relatie.postcode %>
</p>

<p>
  <strong>Plaats:</strong>
  <%= @relatie.plaats %>
</p>

<p>
  <strong>Omschrijving:</strong>
  <%= @relatie.omschrijving %>
</p>

1 个答案:

答案 0 :(得分:1)

查看您提供的错误,表明naam没有nil:NilClass方法。这意味着您正在调用给定对象(nil)不存在的方法。查看代码,这意味着@relatie中未正确设置show。即Relaties.find(params[:id])正在返回nil

这很可能是@relatie.save错误导致失败,导致redirect_to @relatie重定向到nil。查看您的createrake routes,您确定不应该使用Relaty.new而不是Relaties.new

正如@RedZagogulin所提到的,错误的来源是您的show定义在private标记下,这意味着show是私有方法,并且无法通过调用访问。因此,@relatie未设置。只需将其移到标签上方就可以解决您的问题。