I'v got problem with Active Storage under Rails 7.
I read some posts but all are about Rails 5-6 and some methods was depreciated since then.
Problem - when I try to upload second photo, old is deleted. Why? How to fix this?
I have model:
class Profile
has_many_attached :photos
has_one_attached :avatar
in controller:
class ProfilesController < ApplicationController
def update
Rails.logger.debug params.inspect
@profile = current_user.profile
@profile.update(profiles_params)
private
# Only allow a list of trusted parameters through.
def profiles_params
params.require(:profile).permit(:id, :email, :marketing,
:marketing_second, :terms,
:personal_data,
:birthdate, :avatar, :photos )
end
in view:
<%= form_for @profile do |f| %>
<div class='upload_container'>
<%= f.file_field :photos, accept:'image/*',
:class=>'file_field_custom', required: true %>
<%= f.button "Upload", type:'submit', :class=>'photos_submit_button' %>
</div>
<% end %>
This was removed from Rails 7:
config.active_storage.replace_on_assign_to_many = false
logs:
#<ActionController::Parameters {"_method"=>"patch",
"authenticity_token"=>"y5n4UgRhRWFB9Q0L3J1roxK3dhuijRQk7Fng6sjHU52G0KDs9OJlYt8nmshG8HYnlrk7JB9x3QHDO8_GQnDwsA", "profile"=>{"photos"=>#<ActionDispatch::Http::UploadedFile:0x00007f9773f3db78 @tempfile=#Tempfile:/tmp/RackMultipart20230119-3094-gapmw4.jpg, @original_filename="saturn-planet-3200-1200-1966.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name="profile[photos]"; filename="saturn-planet-3200-1200-1966.jpg"\r\nContent-Type: image/jpeg\r\n">}, "controller"=>"profiles", "action"=>"update", "id"=>"abcd"} permitted: false>
[1m[36mProfile Load (0.6ms)[0m [1m[34mSELECT profiles
.* FROM profiles
WHERE profiles
.user_id
= 1 LIMIT 1[0m
↳ app/models/user.rb:59:in `profile'
[1m[36mActiveStorage::Attachment Destroy (4.4ms)[0m [1m[31mDELETE FROM
`active_storage_attachments` WHERE `active_storage_attachments`.`id` = 334[0m
↳ app/controllers/profiles_controller.rb:133:in `update'
Why action Destroy is fired.
CodePudding user response:
@profile.photos.attach(params[:profile][:photos])
in update action of your controller