I have a basic eRuby each loop
<% @product_images.each do |image|%>
<% if @counter < 4 %>
<% p 'Im in here' %>
<% else %>
<% return %>
<% end %>
<% @counter += 1 %>
<% p @counter %>
<% end %>
Inside my loop i have an if
statement that checks if @counter
is <
than 4
.
Controller code
def show
productId = params[:id]
@product_images = ProductImage.where("product_id = ?", productId)
@counter = 0
end
When i run this code it should return once the counter is greater than 4 but i get an error that says no implicit conversion of nil into String
This is pretty straight forward code i can't seem to figure out what i'm doing wrong. It seems like it's breaking in the line
<% if @counter < 4 %>
Here is a picture of the error:
It looks like you are trying to limit the number of @product_images
that are rendered in your view. Instead of using @counter
, you should simply limit the number of @product_images
in your controller, something like:
def show
@product = Product.find_by(id: params[:id])
@product_images = @product.product_images.limit(4)
end
And then in your view, do something like:
<% @product_images.each do |image| %>
# do stuff
<% end %>
This, naturally, assumes that:
class Product < ActiveRecord::Base
has_many :product_images
end
And:
class ProductImage < ActiveRecord::Base
belongs_to :product
end
You could put that logic back in the view, like:
<% @product.product_images.limit(4).each do |image| %>
# do stuff
<% end %>
And then your show
action could be just:
def show
@product = Product.find_by(id: params[:id])
end
But, I prefer leaving it in the controller to reduce the coupling between your views and your models.