【发布时间】:2016-01-06 09:36:52
【问题描述】:
我有一个包含许多图像的目录项,并尝试使用嵌套表单和载波通过一个请求上传所有图像。我也使用响应器、haml 和简单的形式。 所以,它是这样的:
item.rb
class Item < ActiveRecord::Base
has_many :images, dependent: :destroy
accepts_nested_attributes_for :images
end
image.rb
class Image < ActiveRecord::Base
belongs_to :item
mount_uploader :image, ImageUploader
end
_form.html.haml
= simple_form_for(@item, :html => {:multipart => true }) do |f|
= f.error_notification
.form-inputs
= f.input :name
= f.input :description
= f.input :price
= simple_fields_for :images do |image|
= image.file_field :image, multiple: true
.form-actions
= f.button :submit
items_controller.rb
...
def new
@item = Item.new
respond_with(@item)
end
def create
@item = Item.new(item_params)
@item.save
respond_with(@item)
end
...
def item_params
params.require(:item).permit(
:name, :description, :price,
image_attributes: [:image]
)
end
我是 Rails 新手,它显然没有按照我想要的方式工作。它保存项目并完全忽略所有图像。
所以,我想知道,有没有办法实现我的目标,而不需要像
这样的结构def create
@item = Item.new(item_params)
params[:images].each do |image|
img = Image.new
img.image = image
@item.images << img
end
@item.save
respond_with(@item)
end
【问题讨论】:
标签: ruby ruby-on-rails-4 file-upload carrierwave nested-forms