【问题标题】:Why do i get this error (NoMethodError)为什么我会收到此错误(NoMethodError)
【发布时间】:2017-08-21 15:25:07
【问题描述】:

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

这是我的问题的图像:

这是我的 cloud 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

【问题讨论】:

  • 您的迁移文件中的数据有误。我建议你阅读guides.rubyonrails.org/getting_started.html
  • 这里的缩进实际上是不存在的,这确实损害了可读性。在提出问题时,请努力使您的代码尽可能干净和美观。让其他人难以理解正在发生的事情是不好的。
  • 我很抱歉我是堆栈溢出的新手,我不打算让人们挣扎,我已经改变并尽力从我的代码中复制它

标签: ruby-on-rails ruby ruby-on-rails-4 nomethoderror cloud9


【解决方案1】:

您的迁移似乎缺少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

【讨论】:

  • 我试过了,但它给了我这个 NoMethodError undefined method `title' for #
  • 现在我得到了这个:未初始化的常量 ApplicationRecord
  • 您必须使用较旧的 Rails 版本。而是从ActiveRecord::Base 继承。
  • 我正在使用 Rails 版本:Rails 4.2.5(如果这对您有帮助)
  • 我已经尝试过 ActiveRecord :: Base,现在它给了我错误:#
    的未定义方法`title'
【解决方案2】:

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

这将在您运行迁移时使用 new 关键字创建一个 Article 实例,它将是一个 nil 实例,这就是您收到上述错误的原因

文章编号:无

因为最后一条记录为 nil,而您正在寻找该记录的标题,该记录的主键也为 nil。

【讨论】:

    猜你喜欢
    • 2018-06-22
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-19
    • 1970-01-01
    • 2018-02-24
    相关资源
    最近更新 更多