RoR:Carrierwave无法工作/保存到数据库

时间:2011-12-19 22:54:03

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1 carrierwave

这是我一直试图通过观看Railscast让Carrierwave正常工作。我有一个Post Project页面,用户可以在其中输入项目的详细信息。他们还可以将文件上传到此页面,然后提交项目。所以我在页面上使用了nested_form_for。

new_step_3.html.erb

<%= nested_form_for @project, :html => {:multipart => true} do |f| %>
  <%= f.text_field :title %>
  <%= f.text_field :description %>

    <%= f.fields_for :document do |attachment_form| %>
      <%= attachment_form.file_field :title %>
    <% end %>

  <%= f.text_field :skills %>
  <%= f.submit 'Post Project' %>
<% end %>

project.rb模型

attr_accessible :category, :title, :budget, :end_date, :description, :skills, :document, :days_lasting, :documents_attributes

belongs_to :user
has_many :posts
has_many :documents, :as => :attachable

validates_presence_of :category, :title, :description, :skills

accepts_nested_attributes_for :documents

document.rb model

attr_accessible :project_id, :title, :document

belongs_to :user
belongs_to :project
has_many :posts

mount_uploader :document, DocumentUploader

projects_controller.rb

def create
@project = current_user.projects.build(params[:project])

respond_to do |format|
  if @project.save
    format.html { redirect_to project_step_4_path(:start => @project.id), notice: 'Project was successfully created.' }
    format.json { render json: @project, status: :created, location: @project }
  else
    format.html { render action: "new" }
    format.json { render json: @project.errors, status: :unprocessable_entity }
  end
end

现在,当我尝试提交表单时,它会说未知属性:document app / controllers / projects_controller.rb:85:在'create'

在Rails控制台中运行命令工作Document.create!(:document =&gt; File.new(“test.jpg”))

1 个答案:

答案 0 :(得分:2)

我认为应该是

<%= f.fields_for :documents do |attachment_form| %>
  <%= attachment_form.file_field :title %>
<% end %>

使用fields_for:文档

这就是为什么它找不到document属性。您的表单可能会发送类似的哈希:

{
  :project => {
    :title => "blabla",
    :document => {...}
  }
}

并且它不知道如何处理该文档。 现在,您的嵌套文档将位于:documents =&gt; {}和accepts_nested_attributes_for,它应该有用。

您必须build控制器中此项目的文档:

@project.documents.build