表单在rails中提交不起作用,可能的路由/路径错误不确定为什么?

时间:2014-06-09 12:04:24

标签: ruby-on-rails forms rails-activerecord rails-routing

我正在尝试在rails中提交一个只是pdf uplaod的表单(使用paperclip)。我的表格,控制器或模型都有问题,我不确定是哪一个。

这是我的表格:

<%= 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

我添加了文件并按上传,但我被重定向到&#39; update.html.erb&#39;。 该文件不存在于db中,只是一个空记录。

当我按下uplaod调试params时,我得到了这个输出

    {"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\"\r\nContent-Type: application/pdf\r\n">}, "commit"=>"Add Event", "action"=>"update", "controller"=>"year", "id"=>"9"}

========================= 修改

好的,所以与我的命名不一致导致了preiosu错误,我再次开始,产生:

 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,感谢您的帮助和耐心。

2 个答案:

答案 0 :(得分:2)

控制器没有做它应该做的事情。这是在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

编辑:

您必须将routes.rb更新为

resources :years

答案 1 :(得分:0)

由于您正在创建yearguide对象,因此rails会推断您必须执行put / patch请求,因此请求将更新,因为rails获取id。

您有两种选择。   1)改变如下控制器的新方法

class YearController < ApplicationController

 def new
   @yearguide = Year.new
 end
end

2)通过将方法参数作为“post”传递给表单标记

来覆盖方法参数