_path的未定义方法,但路由存在

时间:2013-05-02 15:56:15

标签: ruby-on-rails activerecord model routing

当我创建一个新的“car_image”时,我收到Rails错误...... AJAX响应是

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

路线定义

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

然而,路线设置,我可以看到它,当我耙路线,所以我不知道是什么问题。我在我的模型方法中使用路线:

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

这会导致未定义的方法是什么?记录确实保存,但我收到错误响应......

2 个答案:

答案 0 :(得分:2)

由于您需要模型中的链接(不应该是),请在内部添加:

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

然后替换:

car_image_path(:id => id)

使用:

url_helpers.car_image_path(self)

答案 1 :(得分:0)

您没有在资源上定义:show方法,因此它不会创建show路由,也不会为您提供car_image_path方法。

如果你想要car_image_path方法(它接受一个参数,哪个应该是你想要路径的汽车图像),请将路由更改为:

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

但是,如果您只是寻找所有汽车图片的路径,car_images_path就是您要找的。