Я близко ... очень близко ... Я могу загружать отдельные файлы очень хорошо ... но когда я изменяю тип моей формы file_field
на :multiple => true
, чтобы я мог загрузить несколько изображениймои загруженные файлы сразу же обертываются в массив ... и "волшебство" of accepts_nested_attributes_for` теряется.
Редактировать: После дополнительного изучения мне интересно, нужно ли мне вообще беспокоитьсяс accepts_nested_attributes_for
?Возможно, мне просто нужно иметь file_field, :multiple => true
в моей форме галереи (в отличие от вложенной формы), а затем в моем действии создания создать новую галерею, а затем, так сказать, вручную пройтись по каждому элементу в массиве params[:gallery][:photos_attributes]["0"][:image]
,вызывая @gallery.photos.create
для каждого элемента.?!?Кажется громоздким ... но это все, что я могу придумать.
Надеясь, что кто-то с большим опытом работы с Rails может услышать ...
Параметры:
{"utf8"=>"✓",
"authenticity_token"=>"9jXvIwcllct7UyUfo6cvhEucQf2u3SY50SuaCLtFO4c=",
"gallery"=>{
"name"=>"First Gallery",
"photos_attributes"=>{"0"=>{
"image"=>[
#<ActionDispatch::Http::UploadedFile:0x00000104b78978
@original_filename="first_test_image.jpg",
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"gallery[photos_attributes][0][image][]\"; filename=\"first_test_image.jpg\"\r\nContent-Type: image/jpeg\r\n",
@tempfile=#<File:/var/folders/bQ/bQYZC2ukFZCvbKzEDGRtJE+++TI/-Tmp-/RackMultipart20110622-4459-vz78ee>>,
#<ActionDispatch::Http::UploadedFile:0x00000104b78950
@original_filename="second_test_image.jpg",
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"gallery[photos_attributes][0][image][]\"; filename=\"second_test_image.jpg\"\r\nContent-Type: image/jpeg\r\n",
@tempfile=#<File:/var/folders/bQ/bQYZC2ukFZCvbKzEDGRtJE+++TI/-Tmp-/RackMultipart20110622-4459-1jzhhyg>>
]
}
}
}, "commit"=>"Save", "action"=>"create", "controller"=>"galleries"}
#app/models/gallery.rb
class Gallery < ActiveRecord::Base
has_many :photos, :dependent => :destroy
accepts_nested_attributes_for :photos
end
#app/models/photo.rb
class Photo < ActiveRecord::Base
belongs_to :gallery
mount_uploader :photo, PhotoUploader
end
#config/routes.rb
resources :galleries do
resources :photo, :only => [:create, :destroy]
end
ГалереиКонтроллер
def new
@gallery = Gallery.new
@gallery.photos.build
respond_to do |format|
format.html # new.html.erb
format.json { render json: @gallery }
end
end
...
def create
@gallery = Gallery.new(params[:gallery])
respond_to do |format|
if @gallery.save
format.html { redirect_to @gallery, notice: 'Gallery was successfully created.' }
format.json { render json: @gallery, status: :created, location: @gallery }
else
format.html { render action: "new" }
format.json { render json: @gallery.errors, status: :unprocessable_entity }
end
end
end