我已经创建了一个椅子销售网站,此刻我想编辑椅子帖子,无论是谁张贴的。 但是,它为nil:NilClass提供了错误“未定义的方法'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 %>
答案 0 :(得分:1)
您可能将nil
传递给simple_form_for
。我不知道它是如何发生的,让我来描述一下我发现的一些奇怪的事情:
您在控制器中嵌套了错误的方法-#edit
,#update
和#delete
嵌套在create
中。在复制它时您犯了一个错误,或者您有一段非常奇怪的代码。
日志显示用户是从数据库中获取的,但是椅子没有任何作用。这可能是这种行为的原因-@chair
未初始化。
我将做两件事来推动调试的发展:
ChairsController
@chair
中的@edit
是否不为零(例如,将@chair.id
打印到日志中)。