ruby-on-rails - 目录 : Carrierwave Not Working/Saving to Database

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

这是我一起尝试通过观看 Railscast 让 Carrierwave 正常工作的尝试。我有一个发布项目页面,用户可以在其中输入项目的详细信息。他们还可以将文件上传到此页面,然后提交项目。所以我在页面上使用了 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模型

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

结束

现在,当我尝试提交表单时,它会说 unknown attribute: document app/controllers/projects_controller.rb:85:在“创建”中

在 Rails 控制台中运行命令 Document.create!(:document => File.new("test.jpg"))

最佳答案

我觉得应该是

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

with fields_for :文档

这就是它找不到 document 属性的原因。您的表单可能会发送这样的哈希:

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

它不知道如何处理文档。 现在您的嵌套文档将位于 :documents => {} 中,并且使用 accepts_nested_attributes_for,它应该可以工作。

您必须在 Controller 中为该项目构建文档:

@project.documents.build

关于ruby-on-rails - 目录 : Carrierwave Not Working/Saving to Database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8568665/

相关文章:

javascript - 即使没有嵌套路由,Ember Rails 后退按钮也不会渲染模板

ruby-on-rails - 按 JSON 数组中的匹配数查询和排序

ruby-on-rails - 手动路由和 "Couldn' t find User with id=new”错误

Ruby: "Unexpected keyword_end"...但所有的开场白和闭幕式都匹配

postgres中的SQL将重复事件的日期时间转换为 future 的日期时间

ruby-on-rails - apache2 和 mysqldump 导致大量负载平均峰值

ruby - AWS::S3 重命名文件夹

Ruby 在单个脚本中使用助手

ruby-on-rails - 我如何在 Rails 3 中处理来自 Ajax 请求的响应?

ruby-on-rails-3 - 在 Rails 中寻求更细粒度的日志记录选项。如何将整个请求和/或单个过滤器记录到备用日志文件中?