0

In my Rails app, I have projects that have many steps, and each step has many images.

I'm trying to tag links to pages about each step with information about the step, particularly the name of the step and the default image associated with the step.

<%= link_to "", project_step_path(@project, i), :class=> "dot", 
data: {title: steps.find_by_number(i).name, 
image: steps.find_by_number(i).images.order("position ASC").first.file} %>

The title data tag does return the name of the step, but I'm getting an error with my image data tag. When I try it in the rails console, it returns the file path to the image, but when I try to implement it in my app, I get the error undefined method `file' for nil:NilClass.

When I remove "file" from my image tag (so it's image: steps.find_by_number(i).images.order("position ASC").first), and I return what the image data tag is for each link, I get [object Object].

How can I get it to return the right query result?

Here is my steps controller:

class StepsController < ApplicationController

  before_filter :get_project

  def show
    @step = @project.steps.find_by_number(params[:id])
    @image = Image.new
    @images = @step.images.order("position")
    @steps = @project.steps.order("number")
    @numSteps = @steps.count

    respond_to do |format|
      format.html # show.html.erb
      format.json { render :json => @step }
    end
  end
  private
  # get_project converts the project_id given by the routing
  # into an @project object
  def get_project
    @project = Project.find(params[:project_id])
  end
end
scientiffic
  • 9,045
  • 18
  • 76
  • 149

1 Answers1

1

reason for this is the following entire thing becomes nil

images.order("position ASC").first

most possible problem might be is when you select steps by i, there can be a dataset which doesnot have images

to avoid getting this error, one thing you could do is use try

steps.find_by_number(i).images.order("position ASC").first.try(:file)
sameera207
  • 16,547
  • 19
  • 87
  • 152
  • hey, this works! I ended up discovering this right when you were posting your response; because some steps don't currently have images, it wasn't able to find file paths. I'm still running into a problem where the file path is returned as [object Object] - I'm expect it to look like "/image/file/190/01_00.jpg" – scientiffic Feb 10 '13 at 19:03
  • interesting, I tried indexing the object array (didn't know if this was how to do it), but I got the error: undefined method `[]' for /image/file/190/01_00.jpg:FileUploader So it seems like it is getting the file path, but it's attaching this :FileUploader to it? – scientiffic Feb 10 '13 at 19:05
  • glad to help, and if you want to get something like '/image/file/190/01_00.jpg', then you should probably use something like file.file_name. coz I think file is the object, and you need to call the method which returns the file name. – sameera207 Feb 11 '13 at 03:46