如何在 Rails 3.1 中以单一形式创建多个对象?
我有一个照片模型,我想设置一个表单,以便用户可以从同一表单创建多张照片。我看过关于嵌套模型表单的 Railscasts #196 和 197,但这比我需要的更复杂,并且更多地处理包含多个模型的表单,而不是同一模型的多个对象。下面是我的一个简单表单的代码,它允许用户附加图像并创建一个新的照片对象。我已经尝试过 fields_for 并尝试嵌套,但它似乎过于复杂,我无法让它工作。关于如何设置此表单以允许用户附加 5 张图像来创建 5 个新的照片对象,有什么想法吗?
<%= form_for(@photo, :html => { :class => "form-stacked", :multipart => "true" } ) do |f| %>
<div class="clearfix">
<%= f.file_field :image %>
</div>
<div><%= f.submit "Upload", :class => "btn primary" %></div>
<%end %>
I have a Photo model and I want to set up a form so that a user can create multiple photos from the same form. I've watched the Railscasts #196 and 197 on nested model forms but that is more complex than what I need and deals more with forms containing multiple models, not multiple objects of the same model. Below is my code for a simple form that lets a user attach an image and create a new Photo object. I've experimented with fields_for and tried nesting but it seems overly complicated and I can't get it working. Any ideas on how I could set this form up to allow the user to attach 5 images to create 5 new Photo objects?
<%= form_for(@photo, :html => { :class => "form-stacked", :multipart => "true" } ) do |f| %>
<div class="clearfix">
<%= f.file_field :image %>
</div>
<div><%= f.submit "Upload", :class => "btn primary" %></div>
<%end %>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我最终使用 plupload 通过 Carrierwave 进行多个文件(照片)上传。我使用了 plupload-rails gem 和以下代码,一切正常:
希望这可以帮助某人开始工作。
I ended up using plupload for the multiple file (photo) uploads with carrierwave. I used the plupload-rails gem and the following code and all works well:
Hope this helps someone get going.
我喜欢 Ryan Bates Nested_Form gem,因为我很懒。但我会这样做
然后 _photo.erb 部分
关于您的评论:
我认为这就是您正在寻找的,我在这里为您做的(基于 Railscast 载波插曲):
https://github.com/rbirnie/image-upload
基本来源:
画廊模型
绘画模型:
画廊编辑
~
I like Ryan Bates Nested_Form gem, because I'm lazy. But I'd do this
Then a _photo.erb partial
In regards to your comment:
I think this is what you are looking for, I did it for you here (based on Railscast carrierwave episode):
https://github.com/rbirnie/image-upload
Basic source:
Gallery Model
Paintings model:
Galleries edit
~