Joel Grannas
Joel Grannas

Reputation: 2016

undefined method for _path, but route exists

I am getting a Rails error when i create a new "car_image"... the AJAX response is

undefined method `car_image_path' for #<CarImage:0x007fdbb1b79258>

Route defined

resources :car_images, :only => [:index, :create, :destroy]

Rake Routes

car_images GET    /car_images(.:format)                  car_images#index
POST   /car_images(.:format)                  car_images#create
car_image DELETE /car_images/:id(.:format)              car_images#destroy

However, the route is setup and i can see it when i rake routes, so i am not sure what the issue is. I am using the route in my model method:

class CarImage < ActiveRecord::Base
  belongs_to :car

  attr_accessible :description, :image, :title, :car_id, :file

  mount_uploader :file, CarImageUploader

  def to_jq_upload
    {
      "name" => read_attribute(:file),
      "size" => file.size,
      "url" => file.url,
      "thumbnail_url" => file.thumb.url,
      "delete_url" => car_image_path(:id => id),
      "delete_type" => "DELETE" 
    }
  end

end

What would be causing the undefined method here? The record does save, but i get the error response...

Upvotes: 2

Views: 1497

Answers (2)

Jeremy Rodi
Jeremy Rodi

Reputation: 2505

You don't have the :show method defined on the resource, therefore it doesn't create the show route, and doesn't give you the car_image_path method.

If you want the car_image_path method (which takes an argument, which should be which car image you want the path for), change the routing to something like this:

resources :car_images, :only => [:index, :show, :create, :destroy]

However, if you're just looking for the path to all of the car images, car_images_path is what you're looking for.

Upvotes: 0

apneadiving
apneadiving

Reputation: 115521

Since you need a link in a model (which should not be), add this inside:

delegate :url_helpers, to: 'Rails.application.routes'

Then replace:

car_image_path(:id => id)

With:

url_helpers.car_image_path(self)

Upvotes: 2

Related Questions