Domanda

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
È stato utile?

Soluzione

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)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top