0

每个循环我都有一个基本的 eRuby

 <% @product_images.each do |image|%>

        <% if @counter < 4 %>

           <% p 'Im in here' %>
        <% else %>

           <% return %>
        <% end %>

          <% @counter += 1 %>
          <% p @counter %>

 <% end %>

在我的循环中,我有一个if检查 if @counteris <than的语句4

控制器代码

def show

     productId = params[:id]

     @product_images = ProductImage.where("product_id = ?", productId)

     @counter = 0
end

当我运行此代码时,它应该在计数器大于 4 时返回,但我收到一条错误消息no implicit conversion of nil into String

这是非常简单的代码,我似乎无法弄清楚我做错了什么。好像要断线了

<% if @counter < 4 %>

这是错误的图片:

在此处输入图像描述

4

1 回答 1

1

看起来您正在尝试限制@product_images视图中呈现的数量。而不是使用@counter,您应该简单地限制@product_images控制器中的数量,例如:

def show
  @product = Product.find_by(id: params[:id])
  @product_images = @product.product_images.limit(4)
end

然后在您看来,执行以下操作:

<% @product_images.each do |image| %>
  # do stuff
<% end %>

这自然假设:

class Product < ActiveRecord::Base 
  has_many :product_images
end

和:

class ProductImage < ActiveRecord::Base
  belongs_to :product
end

可以将该逻辑放回视图中,例如:

<% @product.product_images.limit(4).each do |image| %>
  # do stuff
<% end %>

然后你的show行动可能只是:

def show
  @product = Product.find_by(id: params[:id])
end

但是,我更喜欢将它留在控制器中以减少视图和模型之间的耦合。

于 2018-04-19T15:20:01.297 回答