【问题标题】:Ruby on Rails - adding an attachment to a nested form. Not submitting / savingRuby on Rails - 向嵌套表单添加附件。不提交/保存
【发布时间】:2015-08-17 01:45:28
【问题描述】:

我有一个应用程序,其中有一个“Gig”模型,它由许多“歌曲”组成。 我希望每首歌曲都有一个用户必须上传的 song_file。

我刚刚安装了回形针 gem(打算很快添加 AWS),但是一旦我添加了 <div class="col-md-4"><%= f.input :song_file, as: :file %></div>,Gig _form 上的“提交”按钮就不再起作用了。

如果我不附加文件,“提交”会正常工作,“歌曲”会更新。但是,一旦我选择了要上传的文件,单击按钮什么也不会发生。

我不知道我做了什么来阻止它...任何帮助将不胜感激!

在 C9.io 上工作

宝石

source 'https://rubygems.org'

gem "paperclip", "~> 4.2"
gem 'cocoon'
gem 'simple_form'
gem 'twitter-bootstrap-rails'
gem 'devise'
etc...

Gig/_form.html.erb

<div class="col-md-6">
  <h2>Define the gig</h2>

<%= simple_form_for(@gig) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= f.input :gig_name %>
    <%= f.input :gig_date, class: "input-append date form_datetime" %>
  </div>
</div>
<div class="col-md-6">
  <h2>Add the songs</h2>

    <%= f.simple_fields_for(:songs) do |song| %>
      <%= render 'song_fields', :f => song %>
    <% end %>
    <div class="links">
      <%= link_to_add_association 'Add Another Song', f, :songs, class: "btn btn-primary col-md-8 col-md-offset-4" %>
    </div>
    <br>
    </div>
  <div class="form-actions">
    <%= f.button :submit, class: "btn-primary col-md-12" %>
  </div>
<% end %>
</div>

演出/_song_fields.html.erb

<div class="nested-fields">
  <div class="row">
    <div class="col-md-4"><%= f.input :name %></div>
    <div class="col-md-4"><%= f.input :singfile %></div>
    <div class="col-md-4"><%= f.input :song_file, as: :file %></div>

    <%= link_to_remove_association "Remove Song", f, class: "btn btn-default btn-danger col-md-4"  %>
  </div>
</div>

Gig_Controller 参数

def gig_params
      params.require(:gig).permit(:gig_name, :gig_date, songs_attributes: [:id, :name, :singfile, :song_file ])
    end

演出模型

class Gig < ActiveRecord::Base
    belongs_to :user
    has_many :songs

    accepts_nested_attributes_for :songs, :reject_if => :all_blank, :allow_destroy => true
end

歌曲模型

class Song < ActiveRecord::Base
  belongs_to :song
  has_attached_file :song_file
end

【问题讨论】:

  • 请在提交表单时将生成的params的hash贴出来。
  • 我假设无论您是否在测试中提供了文件,您都会看到这种行为?
  • @Pavan 我认为没有生成任何东西......只要我将文件上传字段放入表单,“提交”就会停止工作。我也刚刚检查过,“提交”按钮停止工作,只有当我尝试附加文件时。

标签: ruby-on-rails paperclip simple-form


【解决方案1】:

我解决了这个问题,在表单中添加:html =&gt; { :multipart =&gt; true }

`<%= f.simple_fields_for(:songs), :html => { :multipart => true }` do |song| %>
   <%= render 'song_fields', :f => song %>
 <% end %>`

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 2011-03-06
    • 2017-02-25
    • 1970-01-01
    相关资源
    最近更新 更多