eRuby - 在 if 语句中比较数字时没有将 nil 隐式转换为 String

瑞克斯

我有一个基本的 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 %>

这是错误的图片:

在此处输入图片说明

维利安

看起来您正在尝试限制@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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

没有将nil隐式转换为String错误

使用没有 => 的哈希时,没有将 nil 隐式转换为 String

类型错误:没有将 nil 隐式转换为 String

TypeError:没有使用gsub将nil隐式转换为String

TypeError(没有将nil隐式转换为String),仅在生产中

Rails 使用多个数据库 - 没有将 nil 隐式转换为 String

无法更新Calabash-sandbox Ruby“没有将nil隐式转换为String”

全新安装的 Ruby 错误(没有将 nil 隐式转换为 String)

TypeError:没有将nil隐式转换为String。utils.rb:24:in'quote_ident'

TypeError(没有将nil隐式转换为String)生产环境上的Rails devise-jwt gem

Rails:不会将nil隐式转换为String

没有将HTTParty :: Response隐式转换为String

没有将Array隐式转换为String吗?

没有将Hash隐式转换为String(TypeError)

没有将String隐式转换为Integer(TypeError)

没有将 ActiveSupport::HashWithIndifferentAccess 隐式转换为 String?

+:没有将Integer隐式转换为String(TypeError)

ROR +无法将数据存储在数据库中(TypeError异常:没有将nil隐式转换为String)

无法将类型'string'隐式转换为'bool'[If语句]

无法隐式将类型string []转换为string

heroku toolbelt`initialize':没有将nil隐式转换为Hash(TypeError)

控制器规格.reload错误:没有将nil隐式转换为Hash

没有使用ruby将nil隐式转换为整数

无法将类型'string'隐式转换为'decimal'

Ruby将String隐式转换为Integer(typeError)

Unity无法将类型“ string”隐式转换为“ bool”

无法将类型'string'隐式转换为'integer'

Rails,mongoid抛出TypeError不会将nil隐式转换为String

MessagesController#create_message中的TypeError不会将nil隐式转换为String