Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display an array in a rails view?

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?

like image 322
2scottish Avatar asked Nov 01 '12 21:11

2scottish


2 Answers

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.

like image 175
Jimmy Baker Avatar answered Sep 30 '22 17:09

Jimmy Baker


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]
like image 37
joshblour Avatar answered Sep 30 '22 17:09

joshblour