我正在使用Rails 5.1书进行敏捷Web开发。我试图上传图片文件。本书中的示例并没有进入本节中的routes.rb,我显然没有正确理解这一部分,因为加载浏览器时出现此错误:
Routing Error - undefined local variable or method 'applicationController' for main:Object
的routes.rb
Rails.application.routes.draw do
resources :orders
resources :line_items
resources :carts
resources :pictures
root 'store#index', as: 'store_index'
resources :products do
get :who_bought, on: :member
end
get 'upload/new', to: 'upload#get'
end
我一直在尝试其他变体,但总是没有路由匹配错误:
get 'upload/new', to: 'upload#new'
或获取'upload/get', to: 'upload#get'
upload_controller.rb
class UploadController < applicationController
def get //the book uses method 'get', would normally expect 'new'
@picture = Picture.new
end
def picture
@picture = Picture.find(params[:id])
send_data(@picture.data, filename: @picture.name, type: @picture.content_type, disposition: "inline")
end
def save
@picture = Picture.new(picture_params)
if @picture.save
redirect_to(action: 'show', id: @picture.id)
else
render(action: :get)
end
end
def show
@picture = Picture.find(params[:id])
end
private
def picture_params
params.require(:picture).permit(:comment, :upload_picture)
end
end
模型/ picture.rb
不要期望该模型导致路线出现问题,而是为了完整性而添加它。
class Picture < ActiveRecord::Base
validates_format_of :content_type, with: /|Aimage/, message: "must be a picture"
def uploaded_picture=(picture_field)
self.name = base_part_of(picture_field.original_filename)
self.content_type = picture_field.content_type.chomp
self.data = picture_field.read
end
def base_part_of(file_name)
File.basement(file_name).gsub(/[^|w._-]/, '')
end
end
答案 0 :(得分:2)
这里的问题是出错的命名约定。您继承的控制器是ApplicationController
而不是applicationController
根据rails控制器名称的命名约定,始终是CamelCase。有关更多命名约定,请查看此link
您需要将class UploadController < applicationController
替换为class UploadController < ApplicationController
答案 1 :(得分:1)
您的写作不正确applicationController
更改为如下所示
class UploadController < ApplicationController
application
至Application
那就是它,希望它有所帮助