0

画廊控制器.rb

def create
    @gallery = Gallery.new(gallery_params)
      if @gallery.save
          redirect_to @gallery, notice: 'Gallery was successfully created'
        else
          render 'new'
        end
    end

def update
    if @gallery.update(gallery_params)
      redirect_to @gallery, notice: 'Gallery updated'
    else
      render 'edit'
    end
end

def gallery_params
    params.require(:gallery).permit(:title, :description, :image, photos_attributes: [:id, :image, :_destroy])
end

_form.html.erb

<div class="form-group">
    <%= f.fields_for :photos do |photo| %>  
        <% if photo.object.new_record? %>
        <%= render partial: 'photo_fields', locals: {f:f} %>
        <% end %>
    <% end %>   
        <%= link_to_add_association 'Add photo', f, :photos %>
</div>

_photo_fields.erb

<div class="nested-fields">
  <%= f.file_field :image, class: "add-image-field" %>
  <%= link_to_remove_association "Remove", f %>

画廊.rb

class Gallery < ActiveRecord::Base
  has_many :photos, dependent: :destroy

  accepts_nested_attributes_for :photos,
                                reject_if: proc { |attributes| attributes['image'].blank? },
                                :allow_destroy => true

  validates :title, :description, presence: true

照片.rb

class Photo < ActiveRecord::Base
  belongs_to :gallery

  has_attached_file :image

问题是,我可以通过这个表单创建新照片,但是当我尝试编辑它们时,我得到未定义的局部变量或方法“f”。

与当地人一起编辑 解决方案有助于升技,但我仍然无法顺利运行代码。我编辑了我的代码,所以我可以看到当前上传了哪些照片,并添加了一个复选框来删除选定的照片。但是我在尝试这样做时得到了未经许可的参数:_destroy 错误。另外:当我尝试将新照片添加到现有画廊时,我在 GalleriesController#update 中得到 ActiveRecord::UnknownAttributeError。使用多张照片创建新画廊时一切正常。它与当前上传的图片有关,我创建了一个没有照片的画廊,我可以毫无问题地将它们添加到编辑操作中。

 "image"=>#<ActionDispatch::Http::UploadedFile:0x007f6b174119d0 @tempfile=#<Tempfile:/tmp/RackMultipart20141030-3930-zycejb>,
     @original_filename="8e16b83685ab70a561d1facae3a023da.jpg",
     @content_type="image/jpeg",
     @headers="Content-Disposition: form-data; name=\"gallery[image]\"; filename=\"8e16b83685ab70a561d1facae3a023da.jpg\"\r\nContent-Type: image/jpeg\r\n">,
     "_destroy"=>"0",
     "photos_attributes"=>{"0"=>{"id"=>"8"},
     "1"=>{"id"=>"9"}}},
     "commit"=>"Update gallery",
     "id"=>"21"}

因为我没有足够的声誉直接在这里发布图片,所以我粘贴了我的编辑页面当前看起来如何的链接:http: //s13.postimg.org/3o8uvansn/Screenshot_from_2014_11_01_12_55_17.jpg

快速编辑:似乎我修复了更新问题。这条线

<% if photo.object.new_record? %> 

在 _form.html.erb 中让我上传新图片。删除时未经许可的参数的问题仍然存在。

link_to_remove_association

仅删除图片上传的新文件字段,它不会删除已上传的图片。

4

0 回答 0