undefined方法`model_name'代表nil:NilClass - 尝试编辑帖子

问题描述 投票:1回答:1

我已经制作了一个销售网站的椅子,目前我想编辑一个主席职位,无论是谁发布的。然而它为nil:NilClass'提出了一个错误'undefined method`model_name'。不知道为什么。我在编辑表单中只尝试过@chair。我从模型和下面的终端添加了一些代码。

Started GET "/chairs/1/edit" for 127.0.0.1 at 2018-11-27 20:30:53 +0000
Processing by ChairsController#edit as HTML
  Parameters: {"id"=>"1"}
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 3], ["LIMIT", 1]]
  ↳ /Users/benherring/.rbenv/versions/2.4.4/lib/ruby/gems/2.4.0/gems/activerecord-5.2.1/lib/active_record/log_subscriber.rb:98
  Rendering chairs/edit.html.erb within layouts/application
  Rendered chairs/edit.html.erb within layouts/application (3.4ms)
Completed 500 Internal Server Error in 22ms (ActiveRecord: 0.4ms)



ActionView::Template::Error (undefined method `model_name' for nil:NilClass):
    1: <%= simple_form_for @chair do |f| %>
    2: <%= f.input :name %>
    3: <%= f.input :description %>
    4: <%= f.submit :submit %>

app/views/chairs/edit.html.erb:1:in `_app_views_chairs_edit_html_erb___2826282127562707280_70360397910180' . 
class Chair < ApplicationRecord
  belongs_to :user
end



class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
         has_many :chairs
end
class ChairsController < ApplicationController

  def index
    @chairs = Chair.all
  end

  def show
    @chair = Chair.find(params[:id])
    @user = @chair.user
  end

  def new
    @chair = Chair.new
    @user = current_user
  end

  def create
    @user = current_user
    @chair = Chair.new(chair_params)
    @chair.user = @user
    if @chair.save
      redirect_to chairs_path
    end

    def edit
      @chair = Chair.find(params[:id])
      @user = current_user
    end

    def update

    @chair = Chair.find(params[:id])
    @chair.update(chair_params)
    redirect_to chairs_path
    end

    def delete
    end

  end


  private

  def chair_params
    params.require(:chair).permit(:name, :description)
  end
end
<%= simple_form_for [@user, @chair] do |f| %>
<%= f.input :name %>
<%= f.input :description %>
<%= f.submit :submit %>
<% end %>
ruby-on-rails ruby
1个回答
1
投票

你可能会把nil传给simple_form_for。我不知道它是怎么发生的,让我描述一些我发现的奇怪的事情:

你在控制器中有不正确的方法嵌套 - #edit#update#delete嵌套在create中。要么你在复制它时犯了一个错误,要么你有一块非常奇怪的代码。

日志显示用户是从数据库中获取的,但没有关于主席的信息。这可能是这个behaiour的原因 - @chair没有初始化。

我会做两件事来推动调试:

  • 检查方法的嵌套。
  • 确保ChairsController没有定义两次
  • 检查@chair中的@edit是否为零(例如,将@chair.id打印到日志中)。
© www.soinside.com 2019 - 2024. All rights reserved.