我有一个编辑表单,用户可以在其中添加图像。表格属于'画廊'模型,图像是儿童模型'展览图像'。我可以编辑标题,因为它属于父模型,但是我附加的图像将显示为nil(如果我在没有rails image_tag的情况下显示它们,我会得到类似于这个ExhibitionImage id:1,image_file_name:nil,image_content_type:nil, image_file_size:nil,image_updated_at:nil,gallery_id:8,created_at :)。我想象它是我对嵌套表单的实现,我不太明白。
这是相关代码:
画廊控制器
def update
@gallery = Gallery.friendly.find params[:id]
respond_to do |format|
if @gallery.update(gallery_params)
format.html { redirect_to @gallery, notice: 'Gallery was successfully updated.' }
format.json { render :show, status: :ok, location: @gallery }
else
format.html { render :edit }
format.json { render json: @gallery.errors, status: :unprocessable_entity }
end
end
end
def edit
@gallery = Gallery.friendly.find params[:id]
@image = @gallery.exhibition_images.new
end
画廊模特
class Gallery < ActiveRecord::Base
extend FriendlyId
friendly_id :title, use: :slugged
belongs_to :guide
has_many :exhibition_images, :autosave => true
accepts_nested_attributes_for :exhibition_images
end
展览图片
class ExhibitionImage < ActiveRecord::Base
belongs_to :gallery, :autosave => true
has_attached_file :image, styles: { small: "100x100", guide: "500x500" }
validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
end
编辑表格
<%= bootstrap_form_for(@gallery, :html => {:multipart => true}, layout: :horizontal, label_col: "col-sm-2", control_col: "col-sm-10") do |f| %>
<%= f.text_field :title %>
<%= f.fields_for :exhibition_images do |f| %>
<%= f.file_field :image, help: "Ensure images are minimum 400x400px" %>
<% end %>
<%= f.submit "Create/Update", class: "btn btn-primary" %>
<% end %>
如何将附加的图像保存到数据库中??
答案 0 :(得分:0)
好的,我需要将此行添加到我的params方法
params.require(:gallery).permit(:title, exhibition_images_attributes: [:image])
'exhibition_images_attributes'而不是模型属性。不知道为什么,但它确实有效。