我有一个基本的 eRuby 每个循环
<% @product_images.each do |image|%>
<% if @counter < 4 %>
<% p 'Im in here' %>
<% else %>
<% return %>
<% end %>
<% @counter += 1 %>
<% p @counter %>
<% end %>
在我的循环中,我有一个if
检查 if @counter
is <
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 %>
这是错误的图片:
看起来您正在尝试限制@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
但是,我更喜欢将它留在控制器中以减少视图和模型之间的耦合。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句