0

I have a some code in my controller:

def index
 @tasks = Task.paginate(page: params[:page], per_page: 12 )    
 @tasks_row = task_to_rows(@tasks)

 respond_to do |format|
  format.html # index.html.erb
  format.json { render json: @tasks }
 end
end

task_to_rows:

def task_to_rows(tasks)
  item_at_row = 0
  task_row = Array.new
  for i in (0..tasks.length)
    item_at_row += 1
    if item_at_row == 1
      temp_arr = Array.new
      temp_arr << tasks[i]
      task_row << temp_arr
    elsif item_at_row <= 3
      temp_arr << tasks[i]
      task_row << temp_arr
    end
    item_at_row = 0 if item_at_row == 3
  end

  return task_row
end

Method is needed to that each element of the array was an array of three elements. And to be able to show information like this: https://www.evernote.com/shard/s8/sh/5dee1bbd-af05-4432-9e24-586de98f4452/a8229d8d3fd0bb222a76a927a70ee507

In view I have:

<% @tasks_row.each do |task3| %>
  <h3>Row</h3>
  <% task3.each do |task| %>
    <%= task.name %>
  <% end -%>
<% end -%>

But Rails display a error:

undefined method `name' for nil:NilClass

If debug, then all works fine and shows.

UPDATE: In the final version I just need to display the data in this format:

<div class="row>
  <div class="span3">Some data</div>
  <div class="span3">Some data</div>
  <div class="span3">Some data</div>
</div>
<div class="row">
  <div class="span3">Some data</div>
  <div class="span3">Some data</div>
  <div class="span3">Some data</div>
</div>
.........
3
  • hm, what does <% @tasks_row.each do |task3| %> <%= task3 %> <% end -%> return or what does the final array structure look like?? Commented Mar 31, 2013 at 15:21
  • <% @tasks_row.each do |task3| %> <h3>Row</h3> <%= task3 %> <h3>end Row</h3> <% end -%> it return evernote.com/shard/s8/sh/7a79cae1-0604-4047-9019-d4ea35d527c3/… Commented Mar 31, 2013 at 15:25
  • are you getting data in @tasks when you are not in debug mode? Commented Mar 31, 2013 at 15:29

1 Answer 1

1

If I understand task_to_rows correctly, you want the array grouped by 3 right? In that case, I suggest you use each_slice(3) instead. The method you added is error prone and may result to some nil elements which causes the error. Remember that tasks[i] can become nil if i is greater than or equal to the length of your array. This is most probably where the error comes in since you are using tasks.length. So you have 2 choices.

Choice 1

Change

for i in (0..tasks.length)

to

for i in (0..(tasks.length - 1))

Choice 2

Use each_slice(3)

@tasks_row = @tasks.each_slice(3)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.