Mason SB
Mason SB

Reputation: 525

Iterating a table with .slim

I am working on a table for a User Detail Page. My objective is to cut the table into half so its not one long list. I am trying to use an algorithm to put list of projects into two different arrays and then create the two tables from these arrays. I have never coded with slim but this is the project! My algorithms aren't the best practices and right now it is printing more and more projects per row...

    table
      - col1 = [], col2 = []
      - @user.projects.each_with_index do |project,index|
            - if index%2==0
                - col1 = col1.push(project.name)
            - else 
                - col2 = col2.push(project.name)

                <tr>
                <td> #{col1} </td>
                <td> #{col2} </td>
                </tr>

Upvotes: 0

Views: 1201

Answers (2)

7urkm3n
7urkm3n

Reputation: 6321

Personally never used slim, but you can do smth like this, nor check 2nd option.

1)

table
  - @user.projects.each_with_index do |project,index|
        tr
          - if index%2==0
               td.some_class{:style=>'colord: red;'} "#{project.name}"
          - else 
               td "#{project.name}" 

2)

 table
     - col1 = [], col2 = []
     - @user.projects.each_with_index do |project,index|
        - if index%2==0
            - col1.push(project.name)
        - else 
            - col2.push(project.name)

   #make sure tr is outside if @user.each loop block
     tr
       - col1.each do |c1_name|  
           td "#{c1_name}" 

       - col2.each do |c2_name|
           td "#{c2_name}" 

Upvotes: 1

rks
rks

Reputation: 185

I would rather suggest you do pagination instead of chopping up activerecords into multiple arrays and put your logic in controller and model files.

Here's a good gem to do this: https://github.com/mislav/will_paginate

Controller logic assuming theres one to many relation between user and projects

def method
  @user = #User retrieval logic
  @user_projects = Project.where(user_id: @user.id).paginate(:page => params[:page], :per_page => 30)
end

and have your slim code in view file as:

table
  tr
    th Project Name
  -@user_projects.each do |project|
    tr
      td=project.name

=will_paginate @user_projects

I hope this makes sense

Upvotes: 0

Related Questions