为什么我会收到此错误 (NoMethodError)

Why do i get this error (NoMethodError)

我的 ruby on rails cloud 9 代码有问题,而我的任务是从 UI 创建一篇文章并在我点击时将其保存到数据库提交。

这是我的问题图片:

这是我的云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'
end

文章管理员(articles_controller.rb):

class ArticlesController < ApplicationController
  def new
    @article = Article.new 
  end
end 

new.html.erb 在视图中的文章文件夹中:

<h1>Create an article</h1>

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

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

<% end %>

文章模型(article.rb):

class Article < ActiveRecord::Base

end

我完成了迁移,这是我的迁移文件:

class CreateArticles < ActiveRecord::Migration
  def change
    @article = Article.new

    create_table :articles do |t|
      t.string :title
    end
  end
end

您的迁移似乎缺少 title

class CreateArticles < ActiveRecord::Migration
  def change
    create_table :articles do |t|
      t.string :title
    end
  end
end

此外,您的模型应继承自 ApplicationRecord

class Article < ApplicationRecord
end

或者 ActiveRecord::Base 如果你的 Rails 版本低于 5

class Article < ActiveRecord::Base
end

您应该从迁移文件中删除行 @article = Article.new

这将使用 new 关键字创建一个 Article 实例,而您将 运行 迁移并且它将是一个 nil 实例,这就是您出现上述错误的原因

Article id: nill

因为最后一条记录为 nil,而您要查找主键也为 nil 的那条记录的标题。