繁体   English   中英

嵌套属性表格,图片未保存RAILS

[英]nested attributes form, image not being saved RAILS

我有一个编辑表单,用户可以在其中添加图像。 表单属于“图库”模型,图像属于子模型“展览图像”。 我可以编辑标题,因为它属于父模型,但是我附加的图像显示为nil(如果我在没有rails image_tag的情况下显示它们,我将得到如下展览图片ID:1,image_file_name:nil,image_content_type:nil, image_file_size:无,image_updated_at:无,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 %>

如何获取附件图像保存到数据库!

好的,我需要将此行添加到我的params方法中

  params.require(:gallery).permit(:title, exhibition_images_attributes: [:image])

“ exhibition_images_attributes”而不是模型属性。 不知道为什么,但是它起作用了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM