[英]Why do i get this error (NoMethodError)
我在ruby on rails cloud 9代码上遇到问题,而我的任务是从UI创建文章并将其提交到数据库时将其保存到数据库中。
这是我对问题的看法:
这是我的云9代码
route.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
视图中articles文件夹中的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实例,这就是为什么出现上述错误的原因
商品号:nill
因为最后一个记录为nil,而您正在寻找该记录的标题,哪个主键也为nil。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.