Artem
Artem

Reputation: 77

How to fix 'NoMethodError' error in views Ruby

I got a problem NoMethodError in Cards#card_list.

I has a problem, it says problem in 3 line:

.placeholder2.container.visible.card_list.row
- items.each_with_index do |cards, i|
.col-md.card-column{data: {color: cards[4].first.color, type: cards[4].first.card_class}}
  %h4
    %span{class: "icon-#{i == 4 ? ico_item : icon}"}
      = entities[i]

In log file it say:

ActionView::Template::Error (undefined method `first' for nil:NilClass):

My full code in this template:

.placeholder2.container.visible.card_list.row
- items.each_with_index do |cards, i|
.col-md.card-column{data: {color: cards[1].first.color, type: cards[1].first.card_class}}
  %h4
    %span{class: "icon-#{i == 4 ? ico_item : icon}"}
      = entities[i]
  - cards[1].each do |card|
    .col-md-12.card_line.tooltip-card{style: "padding:0px;margin:0;", data: {id: card.id, color: card.color, type: card.card_class, rarity: card.rarity, set: card.card_set, eng_title: card.eng_title&.downcase || '', title: card.title&.downcase}}
      = link_to card, class: "#{color_class(card.color)}-card-tooltip card-tooltip", target: '_blank' do
        %div.cards_gr{class: "bg1_#{color_class(card.color)}", style: "border-left: 4px solid #{rarity_color(card.rarity)};"}
          %div{:style => "padding-right: 10px;float:left;"}
            - if card.card_class == 1
              = image_tag card.hero_icon.url(:small), width: '20px', height: '20px', style: "margin-top:-4px;"
            - elsif card.card_class == 3
              %span{:style => "font-size:14px;font-weight:bold;"}= card.item_gold
            - else
              %span{:style => "font-size:14px;font-weight:bold;"}= card.manacost
          = card.title

How i can fix it?

Upvotes: 2

Views: 74

Answers (2)

Your problem is that cards[4] is nil, you have to check for that and maybe put some defaults like this:

items.each_with_index do |cards, i|
  if cards[4]
    data = { color: cards[4].first.color,type: cards[4].first.card_class }
  else
    data = { color: 'default', type: 'default' }
  end

  .col-md.card-column{data: data}

end

Upvotes: 1

Tom
Tom

Reputation: 1320

In the first example you have cards[4] and in the second cards[1]. Not sure if that discrepancy is on purpose. You are getting a NoMethodError because there are not 5 elements in the cards array. cards[4] is returning nil.

Upvotes: 1

Related Questions