sir_thursday
sir_thursday

Reputation: 5419

Accessing first row in an object

<% 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

Answers (2)

DV Dasari
DV Dasari

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

Kirti Thorat
Kirti Thorat

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

Related Questions