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



我的应用程序有问题,我现在将为您提供来自应用程序的代码和错误的图片,这是我的任务:我应该从 Ruby on rails 创建一个 Web 应用程序,该应用程序应该创建文章并将它们保存到数据库中。

这是错误的图像: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'

文章.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

新.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

我的架构.rb:

ActiveRecord::Schema.define(version: 20170820190312) do
create_table "articles", force: :cascade do |t|
t.string "title"
t.text   "description"
end
end

在保存对象之前,您需要在create method中实例化对象。

尝试更新create方法,如下所示:

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

我希望这有帮助!

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

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

相关内容

  • 没有找到相关文章

最新更新