如何在视图Ruby中修复“ NoMethodError”错误

时间:2018-12-28 22:18:22

标签: ruby-on-rails ruby

我在Cards#card_list中遇到NoMethodError问题。

我有问题,它在3行中表示问题:

.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]

在日志文件中说:

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

我在此模板中的完整代码:

.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

我该如何解决?

2 个答案:

答案 0 :(得分:1)

在第一个示例中,您有cards[4],在第二个示例中,cards[1]。不知道这种差异是否是故意的。您将获得NoMethodError,因为卡数组中没有5个元素。 cards[4]返回nil

答案 1 :(得分:1)

您的问题是cards [4]为nil,您必须检查一下并可能设置一些默认值,例如:

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