How to iterate 2 different objects in the same each in Rails?

0

I have been trying to iterate 2 different objects in Rails, I have 2 resources one of "News" and other of "articles", then I want the 2 iterate in a parallel way in the same section and be added according to the order of date published within my index, investigating, I managed to find the power to create an array interacion in this way:

lista = [0,1,2,3,4,5]
lista.each do |number|
  puts "Iteración número #{number}" 
end

However, I'm not sure how it could be using the 2 resources mentioned above:

<% list = [@enterprise.articles, @enterprise.news] %>
<% list.each do |article, new| %>
<%= article.name %>
<%= new.name %>
<% end %>

However this form is not quite correct, apparently, I hope you can help me with the concern, I will be attentive to your answers, greetings! = D

PS: I have managed to do it with this:

<% @enterprise.articles.zip(@enterprise.news).each do |(article, new)| %>

    <h5><%= article.name %></h5>
    <h5><%= new.name %></h5>

<% end %>

But if I do not have a story, it does not show me the other article record, it has to be shown wide open and I want it to show independently whether it's even or not

    
asked by Hector Hernandez 17.01.2017 в 21:35
source

2 answers

0

Well, use the Array#zip method to combine each element of several arrays. Here is a small demonstration:

a = [1, 2, 3]
b = [4, 5, 6]
a.zip(b)  #=> [[1, 4], [2, 5], [3, 6]]

For your particular case, it would be enough to do the following:

<% list = [@enterprise.articles, @enterprise.news] %>
<% list[0].zip(list[1]) do |article, new| %>
  <%= article.name %>
  <%= new.name %>
<% end %>

Greetings.

    
answered by 17.01.2017 в 22:00
0

I managed to solve it by doing it this way, and it's perfect:

enterprises_controller.rb

def show
  @items = @enterprise.jobs + @enterprise.products
  @items = @items.sort_by do |item| item.created_at end
  @items = @items.reverse
end

show.html.erb

<% @items = @items.each do |item| %>
  <%= item.name %> | <%= item.created_at %> <br>
<% end %>
    
answered by 20.01.2017 в 20:28