How to display an array in the form of rails?

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

Where should I define an array (model or controller)? Also, how can I reference an array and iterate over its elements in a view?

+4
source share
2 answers

You can just skip it like:

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

But it is much more idiomatic to use partial ones. Create a file representing the item. The file must be in the same directory of views with another new view / show / edit / etc and must be named with an underscore. For example, if I had a list of products in an array, and I wanted to show the list in an index view, I would create a partial name "_food.html.erb" that would contain the markup for this product:

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

Then in index.html.erb I would do all the products as follows:

 <%= render @foods %> 

Rails will look for a partial default and display one for each element of the array.

+12
source

Say array = [1,2,3]. You can display it in the view, just a call inside the erb tag as follows:

 <%= 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 the helper method:

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

How much you can define them, it depends. If this is a static list, you can define them in the model as follows:

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

then access them almost everywhere, calling

 Foo::BAR 

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

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

then call it from the view as follows:

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

Source: https://habr.com/ru/post/1443535/


All Articles