Reputation: 5419
<% question = @questions.try(:first) %>
<h1><%= question.title %></h1>
I'm trying to use the above code to grab the first question from a Questions model, and then display it's title in HTML. However, I'm throwing the error undefined method 'title' for nil:NilClass
Autogenerated RoR files use the question.title
line... why isn't it working here?
Upvotes: 0
Views: 48
Reputation: 729
It looks like @question is nil. Have you assigned @question in your controller action. Can you show your code in your controller action?
Upvotes: 0
Reputation: 53048
question.title
raises error as undefined method 'title' for nil:NilClass
that means question
is set as nil
. You set question
using
<% question = @questions.try(:first) %>
It means either @questions
is nil or there @questions.first
returns nil
.
Make sure that you set @questions
instance variable in the Controller's action which renders this particular view.
def action_name
@questions = Question.all
end
Also, if you just want to show only the first question
record in your view and you are not going to use @questions
anywhere then just set
def action_name
@question = Question.first
end
and use it in the view directly as:
<h1><%= @question.try(:title) %></h1>
Upvotes: 1