Ruby-on-rails 未定义的方法模型名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6430426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:27:15  来源:igfitidea点击:

undefined method model_name

ruby-on-railsruby

提问by Bv202

I'm using the default code created by scaffolding. I haven't changed anything.

我正在使用脚手架创建的默认代码。我没有改变任何东西。

Showing app/views/presences/_form.html.erb where line #1 raised: 
undefined method `model_name' for NilClass:Class

1: <%= form_for(@presence) do |f| %>
2:   <% if @presence.errors.any? %>
3:     <div id="error_explanation">
4:       <h2><%= pluralize(@presence.errors.count, "error") %> prohibited this presence from being saved:</h2>

What is wrong here? I'm never calling a method called "model_name" and this code is automated, so why doesn't it work?

这里有什么问题?我从不调用名为“model_name”的方法,而且这段代码是自动化的,为什么它不起作用呢?

Thanks

谢谢

回答by Zabba

Try adding this to your presences_controllerin the newor other relevant action that is rendering the form:

尝试将此添加到您的presences_controllerinnew或其他呈现表单的相关操作中:

#presuming your model is called Presence
@presence = Presence.new 

回答by Taryn East

The view (and the form_for method) expect to actually have a real Presence model in the @presence variable. An @-variable like this is passed through from the controller, which means that you had to set it up in the controller action.

视图(和 form_for 方法)期望在 @presence 变量中实际拥有一个真实的 Presence 模型。像这样的@-变量是从控制器传递过来的,这意味着您必须在控制器操作中设置它。

In the case of the "new" action - you don't have an existing Presence object that you are playing with (unlike, say "show") - so you need to just set up a blank, new one.

在“新”操作的情况下 - 您没有正在使用的现有 Presence 对象(与说“显示”不同)-因此您只需要设置一个空白的新对象。

The form_for method will take a Presence object like this and: if it's an existing one from the db, will create the correct POST-route to update it. But if it's a new, empty one, will create the correct route for creating a new one.

form_for 方法将采用这样的 Presence 对象,并且:如果它是来自数据库的现有对象,将创建正确的 POST-route 来更新它。但如果它是一个新的、空的,将创建正确的路由来创建一个新的。

Hope that helps...

希望有帮助...