ArticlesController 中的 NoMethodError#create undefined method ‘save’ for nil:NilClass

NoMethodError in ArticlesController#create undefined method `save' for nil:NilClass

我的应用程序有问题,我现在将向您提供应用程序的代码和错误图片,这是我的任务:我应该从 ruby 创建一个网络应用程序rails 应用程序应创建文章并将其保存到数据库中。

这是错误的图像:https://i.stack.imgur.com/hYTkl.png

我的云9码

routes.rb:

Rails.application.routes.draw do
 # The priority is based upon order of creation: first created -> highest 
 priority.
 # See how all your routes lay out with "rake routes".

 # You can have the root of your site routed with "root"
 # root 'welcome#index'
resources :articles

root 'pages#home'
get 'about', to: 'pages#about'

article.rb:

class Article < ActiveRecord::Base

end

articles_controller.rb:

class ArticlesController < ApplicationController

   def new
     @article = Article.new 
   end
    def create
       #render plain: params[:article].inspect
    @article.save 
    redirect_to_articles_show(@article)
    end
    private 
    def article_params 
   params.require(:article).permit(:title, :description)


   end





end

new.html.erb:

创建文章

<%= form_for @article do |f| %>

<p>
    <%= f.label :title %>

    <%= f.text_field:title %>

</p>
<p>
    <%= f.label :description  %>
    <%= f.text_area :description %>

</p>
<p>
    <%= f.submit %>

</p>
    <% end %>

我的迁移文件:

class CreateArticles < ActiveRecord::Migration
  def change

      create_table :articles do |t|
        t.string :title
        t.text :description

    end
  end
end

我的schema.rb:

ActiveRecord::Schema.define(version: 20170820190312) do

  create_table "articles", force: :cascade do |t|
    t.string "title"
    t.text   "description"
  end

end

您在创建操作中的 @articlenil。试试这个

def create
  @article = Article.new(article_params)
  @article.save 
  redirect_to_articles_show(@article)
end

您需要在 create method 中实例化对象,然后再保存它。

尝试像这样更新您的 create 方法:

def create
  @article = Article.new(article_params)

  @article.save
  redirect_to @article
end

希望对您有所帮助!