[英]undefined method `save' for nil:NilClass on controller
I am begging to learn ruby on rails and doing the following I am receiving the following errors: 我乞求学习Rails上的ruby,并执行以下操作,收到以下错误:
NoMethodError in ArticlesController#create ArticlesController#create中的NoMethodError
undefined method `save' for nil:NilClass nil:NilClass的未定义方法“保存”
It has to do with the @article.save 它与@ article.save有关
articles_controllers.rb articles_controllers.rb
class ArticlesController < ApplicationController
def new
@article = Article.new
end
def create
#render plain: params[:article].inspect
@article = Article.new(article_params)
@article.save
redirect_to articles_show(@article)
end
private
def article_params
params.require(:article).permit(:tittle, :description)
end
end
routes.rb 的routes.rb
Rails.application.routes.draw do
root 'pages#home'
get 'about', to: 'pages#about'
resources :articles
end
new.html.erb new.html.erb
<%= form_for @article do |f| %>
<p>
<%= f.label :tittle %><br>
<%= f.text_field :tittle %>
</p>
<p>
<%= f.label :description %> <br>
<%= f.text_area :description %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
undefined method `save' for nil:NilClass
This error means you are calling the save
method on a NilClass object ie nil
. 此错误意味着您正在NilClass对象(即nil
上调用save
方法。
When you do this: @article.save
, for some reason, @article
is nil
here and hence you get that error. 当您执行此操作时: @article.save
,由于某种原因, @article.save
@article
在此处为nil
,因此会出现该错误。 Make sure you populate the @article
object and then call: @article.save
. 确保填充@article
对象,然后调用: @article.save
。
Check your Rails log and put some debugging prints like: puts @article.inspect
before you try to save it or so. 检查您的Rails日志并放置一些调试打印信息,例如: puts @article.inspect
然后再尝试保存它。
The error is here: 错误在这里:
def create
@article = Article.new article_params
@article.save # <- Error
redirect_to articles_show(@article)
end
The error is caused by @article
not being present when you call .save
on it. 该错误是由于在调用.save
时不出现@article
引起的 。
Your code looks good. 您的代码看起来不错。
The error must be caused by some other part of your app - I'm thinking your model. 该错误一定是由您的应用程序的其他部分引起的-我在考虑您的模型。
I would ensure you have the following: 我将确保您具有以下条件:
#app/models/article.rb
class Article < ActiveRecord::Base
#-> also make sure you have the appropriate datatable
end
This should allow you to invoke the .new
method on the class, which will then allow you to call .save
as well. 这应该允许您在类上调用.new
方法,然后您也可以调用.save
。
The error you have is likely either because you don't have your model (which is unlikely because Rails would have failed with an "unrecognized constant" error), or your datatable doesn't exist. 出现错误的原因可能是因为您没有模型(这不太可能是因为Rails会因“无法识别的常量”错误而失败),或者数据表不存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.