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?
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With