Search code examples
ruby-on-railsrubyruby-on-rails-4nomethoderrorcloud9

Why do i get this error (NoMethodError)


I am having a problem with my ruby on rails cloud 9 code while my task is to create an article from the UI and save it to the database when I hit submit.

This is my image of my problem:

enter image description here

This is my cloud 9 code

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 (articles_controller.rb):

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

new.html.erb in articles folder in views:

<h1>Create an article</h1>

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

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

<% end %>

Article model (article.rb) :

class Article < ActiveRecord::Base

end

I have done a migration and this is my migrate file :

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

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

Solution

  • Your migration seems to be missing the title column

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

    Also your model should inherit from ApplicationRecord

    class Article < ApplicationRecord
    end
    

    Or ActiveRecord::Base if your Rails version is less than 5

    class Article < ActiveRecord::Base
    end