2

I am stuck on what seems should have a very simple solution, but I can not find anything that will work! I am iterating results from a table on the index page (which returns a list of states). This works without any problems when multiple records are returned. However, when a single record is returned, I get an error: undefined method 'each' for #

I know it is causing the error when only one record is returned, but I can not find any documentation on how to handle this, especially in the case that 1 or 0 records could be returned.

Code in controller:

@states = State.find(params[:id])

Code in index page:

<ul>
  <% @states.each do |state| %>
    <li>
      <%= state.state_name %>
    </li>
  <% end %>
</ul>
1
  • Do you have multiple states with the same id? Commented Jan 22, 2015 at 15:30

3 Answers 3

4

Because you're using find, when you send multiple ids in the params, multiple records are matched; when you send a single id, a single instance is returned.

To ensure that each time, you get an ActiveRecord::Relation object that you can call each on, change your controller code to the following:

@states = State.where(id: params[:id]) # index action

You mentioned that it is the index view, so the above change should solve your problem.

If it's the show view, then you need to stick with find and change your view to display only one state.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This worked perfectly, and was exactly what I was trying to do! I'm just starting to learn RoR and have only seen find being used in the tutorials. This helped a lot!
1

You need to check if it responds to .each, which is the prime given for knowing if something implements the enumerable module.

if @states.respond_to?(:each)
  # iteration goes here
else
  # single handling goes here

Ofcourse you can also use the .where option in your query which returns always a collection

@states = State.where(id: params[:id])

Comments

0

Scenario 1:-

When record is queried in controller as:

@states = State.find(params[:id])

Then in view it should be like that:

<p><%= @states.state_name %></p>

Scenario 2:-

When record is queried in controller as:

@states = State.all

Then in view it should be like that:

<ul>
  <% @states.each do |state| %>
    <li>
      <%= state.state_name %>
    </li>
  <% end %>
</ul>

Note:- In first scenario it is only one object but in second scenario it is a collection of object or a array of object. And only array are iterated.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.