8

I am very new to Rails, but have some Ruby understanding. How can I display the values of an array in a View in Rails?

Where should I define the array (model or controller)? Also, how can I reference the array and iterate between its members on a View?

2 Answers 2

14

You can just loop through it like:

<% @array.each do |element| %>
  <li><%= element.whatever %></li>
<% end %>

But it's much more idiomatic to use partials. Create a file that represents the element. The file should be in the same view directory with the other new/show/edit/etc view and should be named with an underscore. For example, if I had a list of foods as the array and I wanted to show the list on the index view, I would create a partial called "_food.html.erb" which would contain the markup for a given food:

<div>
  Name: <%= food.name %>
  Calories <%= food.calories %>
</div>

Then in the index.html.erb, I would render all the foods like so:

<%= render @foods %>

Rails will look for the partial by default and render one for each element in the array.

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

3 Comments

Thank you. But, where should I define the array (in the model or controller, etc.)?
Whatever you're rendering in the view should be setup in the controller. The model is used for describing what something is and how it operates. The controller is the glue that attaches the model to what you see on the page.
Note that the second option only works for ActiveModel collections, not general arrays.
7

Say array = [1,2,3]. You can display it in the view by just calling inside erb tag like this:

<%= array %> # [1,2,3]

if you want to iterate through it:

<% array.each do |a| %>
<%= a %> Mississippi. 
<% end %> # 1 Mississippi. 2 Mississippi 3 Mississippi.

or use a helper method:

<%= a.to_sentence %> # 1, 2, and 3

As far as where to define them, it depends. If it's a static list, you can define them in the model like this:

class Foo < ActiveRecord::Base
  BAR = [1,2,3]
end

then access them pretty much anywhere by calling

Foo::BAR

If you are only the array in that particular view, you can assign it to an instance variable in the controller like this:

class FooController < ApplicationController
  def index
    @array = [1,2,3]
  end
end

then call it from view like this:

<%= @array %> # [1,2,3]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.