我有一个目录项目,其中包含许多图像,并尝试使用嵌套表单和CarrierWave通过一个请求上传所有内容。我还使用了responders、haml和simple form。因此,代码大致如下:
item.rb
我对Rails还很陌生,它显然没有按照我想要的方式运作。它保存了项目,但完全忽略了所有图像。
因此,我想知道是否有任何方法可以在不使用类似于...的结构的情况下实现我的目标。
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
name: "item[images_attributes][][image]"
中的额外[]
是让我困惑的地方。 - Dan Tappin