galleries_controller.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 %>
gallery.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
photo.rb
class Photo < ActiveRecord::Base
belongs_to :gallery
has_attached_file :image
The problem is, i can create new photos via this form, but when i try editing them i get undefined local variable or method `f'.
edit solution with locals helped abit , but still, i can't run the code smoothly. i edited my code, so i can see which photos are currently uploaded, and added a check box to delete selected photos. But i get unpermitted params: _destroy error when trying to do that. also: when i try to add new photos to existing gallery, i get ActiveRecord::UnknownAttributeError in GalleriesController#update. Everything works fine when creating new gallery with several photos. it has something to do with currently uploaded pictures, i created a gallery without photos and i could add them on edit action without problems.
"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"}
since i don't have enouhg reputation to post images directly here, i'm pasting a link of how my edit page currently looks liks : http://s13.postimg.org/3o8uvansn/Screenshot_from_2014_11_01_12_55_17.jpg
quick edit: seems that i fixed update problem. this line
<% if photo.object.new_record? %>
in _form.html.erb lets me upload new pictures. the problem with unpermitted paramaters when deleting persists.
link_to_remove_association
only removes new file field for pic uploading, it does not remove already uploaded pic.