1
我有一个应用程序,用户可以创建一个gallery
,他/她可以附上一些图片。我使用carrierwave来达到这个目的,它的结构如下。 每个gallery
有许多pictures
和每个picture
有1 image
。RoR:嵌套字段形式
class Gallery < ActiveRecord::Base
has_many :pictures, dependent: :destroy
accepts_nested_attributes_for :pictures, allow_destroy: true;
end
class Picture < ActiveRecord::Base
belongs_to :gallery
mount_uploader :image, ImageUploader
end
图片上传与下面的表格
<%= form_for(@gallery, html: {multipart: true}) do |f| %>
<%= f.label :title %><br />
<%= f.label :pictures %><br />
<% if @gallery.pictures %>
<ul class="form-thumbs clearfix">
<% @gallery.pictures.each do |picture| %>
<li>
<%= image_tag(picture.image) %>
<%= link_to "Delete", gallery_picture_path(@gallery, picture), method: :delete %>
</li>
<% end %>
</ul>
<% end %>
<%= file_field_tag "images[]", type: :file, multiple: true %>
<% end %>
然后加工具有以下作用
class GalleriesController < ApplicationController
def create
@gallery = Gallery.new(gallery_params)
if @gallery.save
if params[:images]
params[:images].each do |image|
@gallery.pictures.create(image: image)
end
end
end
end
end
这一切运作良好,但现在我想补充一个嵌套场:title
,这样当我打开表格,并且有图片上传时,我可以给每张图片标题。任何人都可以解释我如何适应现有的形式?
谢谢你的回答丰富。即使'图片'表中存在'标题'列,我也会在#<图片::ActiveRecord_Associations_CollectionProxy:0x007f1ee01d7c10>中得到以下错误'未定义方法'标题' – sjbuysse
如果删除'p.text_field:title '测试? –
或多或少,我现在可以加载表格,但是当我提交时我没有创建图片(我也没有在你写的动作中看到它) – sjbuysse