这实际上是一个两部分的问题
作为记录 - 我正在使用 Simple_form、Carrierwave 和 awesome_nested_fields gems。
在我的应用程序中,我有活动,每个活动都有一个演讲者,每个演讲者都有一张图片。图片不是单独的表格,它们存储在“扬声器”下
事件.rb
class Event < ActiveRecord::Base
belongs_to :type
...
has_many :speakers
accepts_nested_attributes_for :speakers, allow_destroy: true
...
扬声器.rb
class Speaker < ActiveRecord::Base
belongs_to :event
mount_uploader :photo, PhotoUploader
end
强参数(事件控制器):
private
def event_params
params.require(:event).permit(:title, :description, :type_id, :price, :program,
:start_date, :end_date, :image, category_ids: [],
speakers_attributes: [ :id, :name, :photo, :status, :description, :url, '_destroy'])
end
照片上传和替换没问题,但是当涉及到编辑时,麻烦就开始了:
编辑表格:
<%= simple_form_for @event, html: {multipart: true} do |f| %>
<%= f.other_stuff %>
<%= f.nested_fields_for :speakers do |f| %>
#Problem 1 - deleting uploaded images
<%= f.check_box :remove_avatar %> # DOES NOT WORK
<%= f.check_box :_destroy %> # DOES NOT WORK
Problem 2 - showing an uploaded image
<%= image_tag(@event.speaker.photo_url) if @event.speaker.photo? %> # Error - undefined method `photo?'
<% end %>
<% end %>
我很确定第一个问题与强参数有关,我尝试了很多变体,但到目前为止我无法找出正确的变体(:photo_remove、[photos_attributes['_destroy']] 等)。
显示上传图片的第二个问题可以通过插入来解决
<%= image_tag @event.speakers[0].photo %>
但是,在我的代码中,如果有多个发言者,我需要更改数组整数,而且我似乎无法弄清楚如何做到这一点(尝试编写辅助方法,但到目前为止没有什么好处)。
任何帮助将不胜感激,谢谢