Reputation: 463
I'm using:
ruby 2.6
rails 6.1.4
devise
devise_token_auth
active-storage
usingl locally disk service
I'm creating api in which I can storage and upload pictures. I can upload pic via Insomnia but problem is when I want to add second image to the same user. Image is just replacing.
user.rb
# frozen_string_literal: true
class User < ActiveRecord::Base
def initialize
self.pictures = []
end
extend Devise::Models #added this line to extend devise model
# Include default devise modules. Others available are:
# :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, :confirmable
include DeviseTokenAuth::Concerns::User
VALID_USERNAME_REGEX= /^(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$/ix
validates :username, presence: true, length: {minimum:3, maximum:26},
format: { with: VALID_USERNAME_REGEX, :multiline => true,
message: :invalid_username }
validate :password_complexity
attr_accessor :pictures
has_many_attached :pictures
validates :pictures, content_type: ['image/png', 'image/jpg', 'image/jpeg'],
size: { less_than: 5.megabytes , message: :invalid_size }
def password_complexity
return if password.blank? || password =~ /^((?!.*[\s]))/
errors.add :password, :invalid_password
end
end
application_controller.rb
class ApplicationController < ActionController::API
include DeviseTokenAuth::Concerns::SetUserByToken
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:account_update, keys: [:pictures, :username, :email])
end
end
All controllers which I use are default from devise_token_auth
. I found tip to add in config/application.rb
config.active_storage.replace_on_assign_to_many = false
but after that I'm always getting status 500
Upvotes: 0
Views: 621
Reputation: 530
The best way to solve this is to open application.rb and inside your module add.
config.active_storage.replace_on_assign_to_many = false
That is all you need to do. It works, Just make sure you save all your files, and restart your server.
You can see in the rails docs it says the following:
Optionally replace existing files instead of adding to them when assigning to a collection of attachments (as in @user.update!(images: [ … ])). Use config.active_storage.replace_on_assign_to_many to control this behavior.
Upvotes: 0
Reputation: 43
I solved a similar problem by adding this to the config/environment/development.rb (as per the Rails Guide):
config.active_storage.replace_on_assign_to_many = false
Good luck!
Upvotes: 1
Reputation: 21
Did you add an array to the parameter so you can store multiple image ?
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:account_update, keys: [:pictures [], :username, :email])
end
Upvotes: 1