2017-08-24 100 views
0

我的應用程序出現問題,我現在將給你的代碼從應用程序和錯誤的圖片,這是我的任務:我應該從軌道上的ruby創建一個Web應用程序,應用程序應創建文章並將其保存到數據庫。ArticlesController中的NoMethodError#創建未定義的方法`保存'爲零:NilClass

這是錯誤的圖像: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' 

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

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

我schema.rb:

ActiveRecord::Schema.define(version: 20170820190312) do 

    create_table "articles", force: :cascade do |t| 
    t.string "title" 
    t.text "description" 
    end 

end 

回答

0

您需要在保存之前實例化create method中的對象。

嘗試更新create方法,像這樣:

def create 
    @article = Article.new(article_params) 

    @article.save 
    redirect_to @article 
end 

我希望這有助於!

0

@article在th e創建動作是nil。試試這個

def create 
    @article = Article.new(article_params) 
    @article.save 
    redirect_to_articles_show(@article) 
end 
相關問題