Reputation: 2003
I'm trying to learn the absolute basics of Ruby on Rails following the Ruby on Rails guide. However, I'm having a problem trying to display a variable initialized in the controller, in the view: both in test and show views it says "undefined method for nil:NilClass"
app/controllers/articles_controller
class ArticlesController < ApplicationController
def new
end
def create
@article = Article.new(article_params)
@article.save
redirect_to @article
end
private
def article_params
params.require(:article).permit(:title, :text)
end
def show
@article = Article.find(params[:id])
end
def test
@testing = [0, 1, 2, 3]
end
end
app/views/articles/new.html.haml
= form_for :article, :url => articles_path do |f|
%p
= f.label :title
%br/
= f.text_field :title
%p
= f.label :text
%br/
= f.text_field :title
%p
= f.submit
app/views/articles/show.html.haml
%p
Title:
%br/
= @article.title
%p
Text:
%br/
= @article.text
app/views/articles/test.html.haml
= @testing[0]
This is the error I get for the show view:
NoMethodError in ArticlesController#show
undefined method `title' for nil:NilClass
Title:
%br/
= @article.title
%p
Text:
%br/
Any help would be really appreciated. I don't see what I'm missing. Thanks
Upvotes: 0
Views: 204
Reputation: 3770
You are using @article in the controller, and @articles in the view. Change @articles to @article in the view.
Also, move the private method to the bottom of the class - the show and test methods are now private in your controller.
class ArticlesController < ApplicationController
def new
end
def create
@article = Article.new(article_params)
@article.save
redirect_to @article
end
def show
@article = Article.find(params[:id])
end
def test
@testing = [0, 1, 2, 3]
end
private
def article_params
params.require(:article).permit(:title, :text)
end
end
Upvotes: 2