Nested understanding of each cycle

I would like to understand how nested loops work each.

Suppose I have a blog application with a model Articleand a model Comment.

Quoting all my articles ...

- @articles.each do |article|
  = article.text

The completion of all my comments ...

- @comments.each do |comment|
  = comment.text

But what I really want is to skip all the comments of a particular article - this means that the second loop is nested inside the first.

How to achieve this?

+4
source share
2 answers

Below is the code

- @articles.each do |article|
  = article.text
  #level of indentation matters.
  - article.comments.each do |comment| #this will loop through respected article comments
    = comment.text
+2
source
- @article.comments.each do |comment|
  = comment.text

Note that this means that you set the @article variable to be equal to the specific Article object that you usually do in the controller.

+2
source

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


All Articles