<% 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?
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>
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加