

質問です。この <% @items.zip(@user〜 のコードにindex 番号をつけたいです。

どなたか分かる方いらっしゃいますか？

Syntax error.

[code]

    <% @items.zip(@user_items).with_index do |item, ui, index| %>
      <td class="invert"><%= index %></td>
    <% end %>
    
[/code]

show.html.erb

[code]

    <% @items.zip(@user_items).with_index do |item, ui, index| %>
    <tr class="rem1">
        <td class="invert"><%= index %></td>
        <td class="invert-image" >
            <%= link_to image_tag(item.img.thumb.url || "sushi1.jpg", class: "img-responsive" ), item %>
        </td>
    
        <td class="invert">
        　　<div class="quantity"> 
            　<div class="quantity-select">                           
                　<div class="entry value-minus">&nbsp;</div>
                　<div class="entry value" id="score-value"><%= ui.quantity %></div>
                　<div class="entry value-plus active">&nbsp;</div>
            　</div>
            </div>
        </td>
        <td class="invert"><%= link_to item.name, item %></td>
        <td class="invert">$ <%= link_to item.price, item %></td>
        <td class="invert">
                <%= link_to image_tag("close_1.png"), item_delete_in_baskets_path(item), method: :post, data: { confirm: "You sure?" }, class:"ml-2"%>
        </td>
    </tr> 
    <% end %>
    
[/code]

baskets_contrller.rb

[code]

    class BasketsController < ApplicationController
      before_action :authenticate_user!
      def show 
        # same as application controller
        
        basket = current_user.prepare_basket
        @user_items = basket.basket_items
        @basket_items = @user_items.select(:item_id)
        @items = Item.where(id: @basket_items)
        @total_price = basket.total_price
      end
    end
    
[/code]


CC BY-SA 4.0
2021-03-08T09:41:16.863
74520
2021-03-09T04:11:04.817
44226
question
ruby-on-rails ruby
railsのeach文 .zip付きでインデックス番号をつけたい


each_with_index または each.with_index を利用すればいいと思います

[code]

    array1 = ["el1", "el2", "el3"]
    array2 = [10, 20, 30]
    array1.zip(array2).each_with_index { |(array1_el, array2_el), index|
      p "#{array1_el}, #{array2_el}, #{index}"
      # "el1, 10, 0"
      # "el2, 20, 1"
      # "el3, 30, 2"
    }
    array1.zip(array2).each.with_index { |(array1_el, array2_el), index|
      p "#{array1_el}, #{array2_el}, #{index}"
      # 同じ
    }
    
[/code]


CC BY-SA 4.0
2021-03-09T04:11:04.817
74538
2021-03-09T04:11:04.817
9796
74520
answer