scientiffic
scientiffic

Reputation: 9415

Rails: undefined method for NilClass running even in false if statement

I have two models: Image and Video. An image belongs to a video sometimes, but not always, but a Video always belongs to an image (this is because I generate a thumbnail image for videos that get uploaded to the site, but users can upload regular images as well that don't have an associated video).

In my view, I go through all images and check if any of the images have an associated video. If it does, then it should create something based on the video's attribute "embed_url".

When I tried running the code, I kept getting the error:

undefined method `embed_url' for nil:NilClass

I didn't understand why, so I made my if statement :if(false)", and I still get the error even though the code should never get to that part of the if statement. What am I doing wrong?

<% step.images.order("position").each_with_index do |image, index| %>

    <% Rails.logger.debug "image #{image.id}"%>

      <script type="text/javascript">
      <% has_video = !image.video.blank? %>

      <% Rails.logger.debug "image #{image.id} has_video: #{has_video}"%>
       var has_video = Boolean(<%=has_video%>);

        // add step images to carousel
        if(<%=index%>==0){

          if(false){
              $('.carousel-inner.<%=step.id%>').append('<div class="item active">
              <div class="flex-video"> <a class="fancybox" href="<%=**image.video.embed_url**%>" rel="gallery <%=step.id%>" data-fancybox-type="iframe"><iframe src="<%=image.video.embed_url%>" id="<%=image.id%>"></iframe></a></div></div>'); 
          }
          else{
           $('.carousel-inner.<%=step.id%>').append('<div class="item active"><a class="fancybox" href="<%=image.image_path_url%>" rel="gallery <%=step.id%>" data-fancybox-type="image"> <%=image_tag(image.image_path_url(:preview), :width => "100%", :id=> image.id)%></a></div>');    
          } 
...
      <% end %>

Upvotes: 0

Views: 82

Answers (1)

Chris Heald
Chris Heald

Reputation: 62698

Your if(false) is Javascript, not Ruby - while the template is being rendered, it's not going to have any bearing on what actually gets executed. Anything in <% ... %> is what gets run serverside, which is what you're having issues with here.

Upvotes: 2

Related Questions