Nesting Carrierwave images in Rails 4

狂风中的少年 提交于 2019-12-25 04:09:06

问题


This is actually a two part question

For the record - I am using Simple_form, Carrierwave and awesome_nested_fields gems.

In my app I have events, each event has a speaker, and each speaker has a picture. Pictures are not a separate table, they're stored under 'speakers'

event.rb

class Event < ActiveRecord::Base

  belongs_to :type
  ...
  has_many :speakers
  accepts_nested_attributes_for :speakers, allow_destroy: true
  ...

speaker.rb

class Speaker < ActiveRecord::Base
 belongs_to :event
 mount_uploader :photo, PhotoUploader
end

strong parameters (events controller):

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

The photos are uploaded and replaced no problem, however when it comes to editing, troubles begin:

edit form:

<%= 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 %>

I am pretty sure the first problem is connected to strong parameters, and I have tried many variations, but so far I couldn't figure out the correct ones (:photo_remove, [photos_attributes['_destroy']], etc).

The second problem with displaying uploaded images can be solved by inserting

   <%= image_tag @event.speakers[0].photo %>

in my code, however if there are several speakers, I need to change the array integer, and I cant seem to figure out how to do that (tried writing a helper method, but nothing good so far).

Any help would be appreciated, thank you

来源:https://stackoverflow.com/questions/18316566/nesting-carrierwave-images-in-rails-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!