我已经制作了一个销售网站的椅子,目前我想编辑一个主席职位,无论是谁发布的。然而它为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 %>
你可能会把nil
传给simple_form_for
。我不知道它是怎么发生的,让我描述一些我发现的奇怪的事情:
你在控制器中有不正确的方法嵌套 - #edit
,#update
和#delete
嵌套在create
中。要么你在复制它时犯了一个错误,要么你有一块非常奇怪的代码。
日志显示用户是从数据库中获取的,但没有关于主席的信息。这可能是这个behaiour的原因 - @chair
没有初始化。
我会做两件事来推动调试:
ChairsController
没有定义两次@chair
中的@edit
是否为零(例如,将@chair.id
打印到日志中)。