Writing for-each loop inside HAML and Rails

10,015

Solution 1

Assuming generics is a string array and you want to separate by new td...

- @my_patients_list.each do |patient|
  %tr
    %td= patient.name
    %td= patient.date_of_birth
    %td= patient.gender
    %td= patient.brand_name.name
    - patient.generics.each do |gen|
       %td= gen.name

Otherwise if you just want to separate by comma...

- @my_patients_list.each do |patient|
      %tr
        %td= patient.name
        %td= patient.date_of_birth
        %td= patient.gender
        %td= patient.brand_name.name
        %td= patient.generics.map(&:name).join(',')  

Solution 2

If you want to seperate the generics name by comma, you may try this:

- @my_patients_list.each do |patient|
  %tr
    %td= patient.name
    %td= patient.date_of_birth
    %td= patient.gender
    %td= patient.brand_name.name
    %td= patient.generics.map(&:name).join(',')           

It will print all associated generic names seperated by comma.

Share:
10,015
Admin
Author by

Admin

Updated on June 17, 2022

Comments

  • Admin
    Admin about 2 years

    I have a HAML like this:

    - @my_patients_list.each do |patient|
      %tr
        %td= patient.name
        %td= patient.date_of_birth
        %td= patient.gender
        %td= patient.brand_name.name
        %td= patient.generics[0].name
    

    notice the line %td= patient.generics[0].name I am cheating and only printing the first generic. But each patinet can have more than one generic. So it is a matter or another for-each loop for that part. But this HAML I just started using it and still not used to it. Can someone help out with that extra loop I should write in HAML format so I can replace it with patient.generics[0].name ? Probably let's just separate their generics names with a comma.

  • matt
    matt almost 11 years
    This will create table rows with varying numbers of td elements, which is likely not be what you want.
  • Bagzli
    Bagzli almost 11 years
    yes, he changed the question after i answered. I edited to reflect the new question.