eRuby - 在 if 语句中比较数字时没有将 nil 隐式转换为 String
eRuby - no implicit conversion of nil into String when comparing numbers in an if statement
我每个循环都有一个基本的 eRuby
<% @product_images.each do |image|%>
<% if @counter < 4 %>
<% p 'Im in here' %>
<% else %>
<% return %>
<% end %>
<% @counter += 1 %>
<% p @counter %>
<% end %>
在我的循环中,我有一个 if
语句来检查 @counter
是否是 <
而不是 4
.
控制器代码
def show
productId = params[:id]
@product_images = ProductImage.where("product_id = ?", productId)
@counter = 0
end
当我 运行 这段代码应该 return 一旦计数器大于 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
但是,我更喜欢将它留在控制器中以减少视图和模型之间的耦合。
我每个循环都有一个基本的 eRuby
<% @product_images.each do |image|%>
<% if @counter < 4 %>
<% p 'Im in here' %>
<% else %>
<% return %>
<% end %>
<% @counter += 1 %>
<% p @counter %>
<% end %>
在我的循环中,我有一个 if
语句来检查 @counter
是否是 <
而不是 4
.
控制器代码
def show
productId = params[:id]
@product_images = ProductImage.where("product_id = ?", productId)
@counter = 0
end
当我 运行 这段代码应该 return 一旦计数器大于 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
但是,我更喜欢将它留在控制器中以减少视图和模型之间的耦合。