Home > other >  After upgrading to Rails 7, errors[:base] not working as expected
After upgrading to Rails 7, errors[:base] not working as expected

Time:04-01

i upgraded my rails app to 7 and see that errors[:base] is no longer working and not validating as expected. record is getting saved even if it is invalid.

below is my validation method code

def file_validation
    if well_list_file.attached?
      if well_list_file.byte_size > 1000000
        errors[:base] << I18n.t('well_list.size_limit')
      end
      if well_list_file.filename.extension_without_delimiter != 'csv'
        Rails.logger.error "in error"
        errors[:base] << I18n.t('well_list.invalid_csv')
      end
    end
  end

controller code below

  def create
    @api_csv = ApiCsv.new(api_csv_params)
    respond_to do |format|
      if @api_csv.save
        format.json { render json: @api_csv, status: :created}
      else
        error_msg = @api_csv.errors.full_messages.join('<br/>')
        format.json { render json: {message: error_msg}, status: :unprocessable_entity }
      end
    end
  end

In the console i see in error but save succeeds.

This was working in rails 5.2. Any help in how to fix this would be great. Thanks.

CodePudding user response:

I can not explain why, but testing it myself i was able to reproduce this error, but using:

errors.add(:base, 'foo')

instead of:

errors[:base] << 'foo'

works and prevents the record from saving.

  • Related