我试图在rails中提交一个表单,这只是一个pdf上传(使用回形针)。我的形式,控制器或模型都有问题,我不确定哪一个。
这是我的表单:
<%= form_for @yearguide, :html => { :multipart => true } do |form| %>
<%= form.file_field :pdf %>
<%= form.submit "Add Event", class: "btn btn-primary" %>
<% end %>
我的控制器:
class YearController < ApplicationController
def new
@yearguide = Year.create(year_params)
end
def create
if @yearguide = Year.save
redirect_to '/'
else
render 'new'
end
end
我的模型:
class YearlyGuide < ActiveRecord::Base
has_attached_file :pdf
validates_attachment :document, content_type: { content_type: "application/pdf" }
end
我的路线:
resources :year
我添加文件并按上传,但我被重定向到'update.html.erb'。该文件在数据库中不存在,只是一条空记录。
当我在按上传时调试参数时,我得到这个输出
{"utf8"=>"✓", "_method"=>"patch", "authenticity_token"=>"G7ZrXEiip/gsqhDObcfYhTT9kerYZGk+Zl29kWA5jos=", "year"=>{"pdf"=>#<ActionDispatch::Http::UploadedFile:0x000001029b0340 @tempfile=#<Tempfile:/var/folders/ns/ry6z7jfd6qg6j8xr2q6dw0yc0000gn/T/RackMultipart20140609-21455-1eg1sk3>, @original_filename="Artsmill Hebden Bridge Exhibition Programme 2014.pdf", @content_type="application/pdf", @headers="Content-Disposition: form-data; name="year[pdf]"; filename="Artsmill Hebden Bridge Exhibition Programme 2014.pdf"rnContent-Type: application/pdfrn">}, "commit"=>"Add Event", "action"=>"update", "controller"=>"year", "id"=>"9"}
=========================编辑
好吧,所以与我的命名不一致导致了前面的错误,我重新开始,生成:
rails g model YearlyGuide pdf:attachment start:datetime end:datetime
rails g controller YearlyGuide new index show
现在我在我的路由中添加了
resources :yearly_guides
当我访问
/yearly_guides/new
我得到这个错误
uninitialized constant YearlyGuidesController
我真的不知道我做错了什么,我以前这样做过,从来没有遇到过这些问题。
@iceman,感谢你的帮助和耐心。
控制器没有做它应该做的事情。这是在Rails中创建新对象的基本框架。
class YearsController < ApplicationController
def new
@yearguide = Year.new
end
def create
@yearguide = Year.create(year_params)
if @yearguide.save
redirect_to '/' # I would consider redirect_to @yearguide to show the newly created object
else
render 'new'
end
end
end
编辑:你必须更新你的路线。rb
resources :years
由于您正在创建yeaguide对象,因此rails推断您必须执行put/patch请求,因此请求将在rails获得id后更新。
你有两个选择。1)更改控制器的新方法,如下
class YearController < ApplicationController
def new
@yearguide = Year.new
end
end
2)通过在表单标签